A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 506. Relative Ranks, the solution in this repository is mainly a greedy 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: greedy.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are sort_indexes, idx, findRelativeRanks.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- 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(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
01//Runtime: 16 ms, faster than 89.15% of C++ online submissions for Relative Ranks.
02//Memory Usage: 11 MB, less than 33.33% of C++ online submissions for Relative Ranks.
03
04class Solution {
05public:
06 template <typename T>
07 vector<size_t> sort_indexes(const vector<T> &v) {
08
09 // initialize original index locations
10 vector<size_t> idx(v.size());
11 iota(idx.begin(), idx.end(), 0);
12
13 // sort indexes based on comparing values in v
14 sort(idx.begin(), idx.end(),
15 [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});
16
17 return idx;
18 }
19
20 vector<string> findRelativeRanks(vector<int>& nums) {
21 vector<size_t> sixs = sort_indexes(nums);
22 vector<string> ans(nums.size());
23 for(int i = 0; i < sixs.size(); i++){
24 int six = sixs[i];
25 //the smaller i means nums[six] larger
26 switch(i){
27 case 0:
28 ans[six] = "Gold Medal";
29 break;
30 case 1:
31 ans[six] = "Silver Medal";
32 break;
33 case 2:
34 ans[six] = "Bronze Medal";
35 break;
36 default:
37 ans[six] = to_string(i + 1);
38 }
39 }
40
41 return ans;
42 }
43};
Cost