Relative Ranks Problem
Description
LeetCode Problem 506.
You are given an integer array score of size n, where score[i] is the score of the i^th athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1^st place athlete has the highest score, the 2^nd place athlete has the 2^nd highest score, and so on. The placement of each athlete determines their rank:
- The 1^st place athlete's rank is "Gold Medal".
- The 2^nd place athlete's rank is "Silver Medal".
- The 3^rd place athlete's rank is "Bronze Medal".
- For the 4^th place to the n^th place athlete, their rank is their placement number (i.e., the x^th place athlete's rank is "x").
Return an array answer of size n where answer[i] is the rank of the i^th athlete.
Example 1:
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1^st, 2^nd, 3^rd, 4^th, 5^th].
Example 2:
Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1^st, 5^th, 3^rd, 2^nd, 4^th].
Constraints:
- n == score.length
- 1 <= n <= 10^4
- 0 <= score[i] <= 10^6
- All the values in score are unique.
Solution
Approach: Sort Indices by Score
An athlete's rank depends on how many athletes scored higher, so sorting gives every placement at once. We cannot sort score itself, though: the answer must stay in the original order. Instead, sort the indices 0 … n-1 by their score, highest first.
- Build
order, the athlete indices sorted byscorein descending order.order[0]is the winner,order[1]second, and so on. - Walk through
orderwith the placementplace(0-based). The athleteorder[place]gets:"Gold Medal","Silver Medal"or"Bronze Medal"forplace0, 1, 2;- the string of
place + 1otherwise, because placements are counted from 1.
- Write each rank to
answer[order[place]], its original position.
The scores are unique, so there are no ties to break. The usual slip is writing the rank to answer[place] instead of answer[order[place]]: that lists the ranks in sorted order rather than by athlete.
Complexity: O(n log n) time for the sort and O(n) space for order and the answer, where n is the length of score.
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
# Athlete indices from the highest score to the lowest.
order = sorted(range(len(score)), key=lambda i: score[i], reverse=True)
answer = [""] * len(score)
for place, athlete in enumerate(order):
if place < 3:
answer[athlete] = medals[place]
else:
answer[athlete] = str(place + 1) # places are 1-based
return answer