← Home

1387. Sort Integers by The Power Value

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
138

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1387. Sort Integers by The Power Value, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue.

The notes already sitting in the source point us in the right direction:

  • map
  • unordered_map

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are getPower, getKth, ids.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//map
02//Runtime: 452 ms, faster than 8.45% of C++ online submissions for Sort Integers by The Power Value.
03//Memory Usage: 49.1 MB, less than 100.00% of C++ online submissions for Sort Integers by The Power Value.
04//unordered_map
05//Runtime: 284 ms, faster than 20.76% of C++ online submissions for Sort Integers by The Power Value.
06//Memory Usage: 47.1 MB, less than 100.00% of C++ online submissions for Sort Integers by The Power Value.
07class Solution {
08public:
09    //map<int, int> power;
10    unordered_map<int, int> power;
11    
12    int getPower(int x){
13        if(x == 1) return 0;
14        
15        if(power.find(x) != power.end()) return power[x];
16        
17        int ans;
18        
19        if(x % 2 == 0){
20            ans = 1 + getPower(x/2);
21        }else{
22            ans = 1 + getPower(3*x+1);
23        }
24        
25        power[x] = ans;
26        
27        return ans;
28    };
29    
30    int getKth(int lo, int hi, int k) {
31        //the larger the earlier to be popped
32        priority_queue<pair<int, int>, vector<pair<int, int>>, less<pair<int,int>>> pq;
33        
34        for(int i = lo; i <= hi; i++){
35            pq.push(make_pair(getPower(i), i));
36            if(pq.size() > k){
37                pq.pop();
38            }
39            // cout << i << " " << power[i] << endl;
40        }
41        
42        //the answer is the largest in k pairs
43        int ans = pq.top().second;
44        
45        return ans;
46    }
47};
48
49//Precompute, partial sort
50//https://leetcode.com/problems/sort-integers-by-the-power-value/discuss/547055/C%2B%2B-8-ms-precompute-and-partial-sort
51//Runtime: 28 ms, faster than 96.47% of C++ online submissions for Sort Integers by The Power Value.
52//Memory Usage: 7.5 MB, less than 100.00% of C++ online submissions for Sort Integers by The Power Value.
53class Solution {
54public:
55    int getPower(int x){
56        if(x == 1) return 0;
57        
58        int ans;
59        
60        if(x % 2 == 0){
61            ans = 1 + getPower(x/2);
62        }else{
63            ans = 1 + getPower(3*x+1);
64        }
65        
66        return ans;
67    };
68    
69    int getKth(int lo, int hi, int k) {
70        vector<int> computed = vector<int>(hi-lo+1, 0);
71        
72        for(int i = lo; i <= hi; i++){
73            computed[i-lo] = getPower(i);
74        }
75        
76        vector<int> ids(hi-lo+1);
77        iota(ids.begin(), ids.end(), lo);
78        
79        nth_element(ids.begin(), ids.begin()+k-1, ids.end(), 
80            [&computed, lo](const int i, const int j){
81                return (computed[i-lo] == computed[j-lo]) ? (i < j) : (computed[i-lo] < computed[j-lo]);
82            });
83        
84        return ids[k-1];
85    }
86};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.