506 Relative Ranks

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example 1:

Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 
For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  • N is a positive integer and won't exceed 10,000.

  • All the scores of athletes are guaranteed to be unique.

The Idea: Use index based hashing. First map the numbers to its index. Then you will be safe to sort the numbers. Initialize an empty arry of strings that are set to the size of the original input container. Next, iterate through the first 3 or less integers in the sorted array, and grab the index that cooresponds to the actual number. Set the value at this relative index to gold, silver, etc.. and use this same strategy to for the remainding ranks.

Complexity: O(N + NlogN) time and space

vector<string> findRelativeRanks(vector<int>& nums) {

    unordered_map<int, int> i_lookup;
    i_lookup.reserve(nums.size());
    for (int i = 0; i < nums.size(); i++) {
        i_lookup.insert({nums[i], i});
    }

    sort(nums.begin(), nums.end(), greater<int>());
    vector<string> ranks(nums.size(), "");
    vector<string> top_ranks = {"Gold Medal", "Silver Medal", "Bronze Medal"};

    for (int i = 0; i < min(3, int(nums.size())); i++) {
        ranks[i_lookup[nums[i]]] = top_ranks[i];
    }

    int remainder = 4;
    for (int i = 3; i < nums.size(); i++) {
        ranks[i_lookup[nums[i]]] = to_string(remainder++);
    }

    return ranks;

}

Last updated