The trick here is to name the state correctly, then let the implementation follow. For 1471. The k Strongest Values in an Array, the solution in this repository is mainly a heap / priority queue solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. 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, greedy.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are getStrongest.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- 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(nlogk)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 968 ms, faster than 52.07% of C++ online submissions for The k Strongest Values in an Array.
02//Memory Usage: 80.6 MB, less than 100.00% of C++ online submissions for The k Strongest Values in an Array.
03class Solution {
04public:
05 vector<int> getStrongest(vector<int>& arr, int k) {
06 int n = arr.size();
07 sort(arr.begin(), arr.end());
08 int median = arr[(n-1)/2];
09
10 sort(arr.begin(), arr.end(),
11 [&median](const int& x, const int& y){
12 return (abs(x-median) == abs(y-median)) ? (x > y) : (abs(x-median) > abs(y-median));
13 });
14
15 return vector<int>(arr.begin(), arr.begin()+k);
16 }
17};
18
19//two pointer
20//https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/674384/C%2B%2BJavaPython-Two-Pointers-%2B-3-Bonuses
21//Runtime: 708 ms, faster than 74.91% of C++ online submissions for The k Strongest Values in an Array.
22//Memory Usage: 80.5 MB, less than 100.00% of C++ online submissions for The k Strongest Values in an Array.
23class Solution {
24public:
25 vector<int> getStrongest(vector<int>& arr, int k) {
26 int n = arr.size();
27 sort(arr.begin(), arr.end());
28 int median = arr[(n-1)/2];
29 int i = 0, j = n-1;
30
31 //remove k weakest values
32 while(k-- > 0){
33 if(median - arr[i] > arr[j] - median){
34 ++i;
35 }else/* if(median - arr[i] <= arr[j] - median)*/{
36 /*
37 when median - arr[i] == arr[j] - median,
38 we choose to move j forward,
39 i.e. to maintain the original arr[j],
40 because arr[j] is larger than arr[i],
41 so arr[j] is also stronger than arr[i]
42 */
43 --j;
44 }
45 }
46
47 //[i, j] are to be removed
48 arr.erase(arr.begin()+i, arr.begin()+j+1);
49 return arr;
50 }
51};
52
53//partial_sort
54//https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/674384/C%2B%2BJavaPython-Two-Pointers-%2B-3-Bonuses
55//Runtime: 1508 ms, faster than 23.09% of C++ online submissions for The k Strongest Values in an Array.
56//Memory Usage: 80.4 MB, less than 100.00% of C++ online submissions for The k Strongest Values in an Array.
57//time: O(nlogk)
58class Solution {
59public:
60 vector<int> getStrongest(vector<int>& arr, int k) {
61 int n = arr.size();
62 if(n == 0) return arr;
63 //quick select, O(n)
64 nth_element(arr.begin(), arr.begin() + (n-1)/2, arr.end());
65 int median = arr[(n-1)/2];
66 //O(nlogk)
67 partial_sort(arr.begin(), arr.begin()+k, arr.end(),
68 [&median](const int& a, const int& b){
69 return abs(a-median) == abs(b-median) ? a > b : abs(a-median) > abs(b-median);
70 });
71 arr.resize(k);
72 return arr;
73 }
74};
75
76//heap
77//https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/674384/C%2B%2BJavaPython-Two-Pointers-%2B-3-Bonuses
78//Runtime: 992 ms, faster than 47.27% of C++ online submissions for The k Strongest Values in an Array.
79//Memory Usage: 85.8 MB, less than 100.00% of C++ online submissions for The k Strongest Values in an Array.
80//time: O(n+klogn)
81class Solution {
82public:
83 vector<int> getStrongest(vector<int>& arr, int k) {
84 int n = arr.size();
85 if(n == 0) return arr;
86 //O(n)
87 nth_element(arr.begin(), arr.begin() + (n-1)/2, arr.end());
88 int median = arr[(n-1)/2];
89
90 //the comp function is the opposite from previous method!
91 //since we want the larger to be popped earlier
92 auto comp = [&median](const int& a, const int& b){
93 return abs(a-median) == abs(b-median) ? a < b : abs(a-median) < abs(b-median);
94 };
95
96 //build heap: O(n)
97 //https://www.geeksforgeeks.org/time-complexity-of-building-a-heap/
98 priority_queue<int, vector<int>, decltype(comp)> pq(arr.begin(), arr.end(), comp);
99
100 //O(klogn)
101 vector<int> ans;
102 while(k-- > 0){
103 ans.push_back(pq.top()); pq.pop();
104 }
105
106 return ans;
107 }
108};
109
110//use nth_element twice!
111//https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/674384/C%2B%2BJavaPython-Two-Pointers-%2B-3-Bonuses
112//Runtime: 456 ms, faster than 98.16% of C++ online submissions for The k Strongest Values in an Array.
113//Memory Usage: 80.6 MB, less than 100.00% of C++ online submissions for The k Strongest Values in an Array.
114//time: O(n)
115class Solution {
116public:
117 vector<int> getStrongest(vector<int>& arr, int k) {
118 int n = arr.size();
119 if(n == 0) return arr;
120 //O(n)
121 nth_element(arr.begin(), arr.begin() + (n-1)/2, arr.end());
122 int median = arr[(n-1)/2];
123
124 //use nth_element to find the k strongest value!
125 nth_element(arr.begin(), arr.begin() + k, arr.end(),
126 [&median](int& a, int& b){
127 return abs(a-median) == abs(b-median) ? a > b : abs(a-median) > abs(b-median);
128 });
129
130 arr.resize(k);
131 return arr;
132 }
133};
Cost