Relative Ranks (LeetCode 506): Solution and Explanation
Given unique athlete scores, return each athlete's rank in input order: "Gold Medal", "Silver Medal" and "Bronze Medal" for the top three, and the placement number as a string for everyone else.
Intuition
The rank of an athlete depends on where their score falls among all scores, so we need the scores in descending order.
But the answer must be in the original order. Sorting the scores alone loses track of who scored what, so keep each score paired with its index.
A max-heap of (score, index) hands out athletes from best to worst. The kth pop is the kth place, and its index tells us exactly which answer slot to fill.
Approach: Max-heap of (score, index)
- Build a max-heap of
(score[i], i)for every athlete. In Python, push(-score, i)intoheapq. - Set
place = 1and createanswerwith n empty slots. - Pop the heap. The popped athlete
igets"Gold Medal","Silver Medal"or"Bronze Medal"for places 1 to 3, andstr(place)otherwise. - Increment
placeand repeat until the heap is empty.
Step-by-step example
score = [5,4,3,2,1]
- Build the max-heap. Its root is 5 (athlete 0).
- Pop 5 (athlete 0): place 1, answer[0] = "Gold Medal".
- Pop 4 (athlete 1): place 2, answer[1] = "Silver Medal".
- Pop 3 (athlete 2): place 3, answer[2] = "Bronze Medal".
- Pop 2 (athlete 3): place 4, answer[3] = "4". Pop 1 (athlete 4): answer[4] = "5".
Code: Python, Java, C++
1class Solution:
2 def findRelativeRanks(self, score: List[int]) -> List[str]:
3 heap = [(-s, i) for i, s in enumerate(score)]
4 heapq.heapify(heap)
5 medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
6 answer = [""] * len(score)
7 place = 1
8 while heap:
9 _, i = heapq.heappop(heap)
10 answer[i] = medals[place - 1] if place <= 3 else str(place)
11 place += 1
12 return answer1class Solution {
2 public String[] findRelativeRanks(int[] score) {
3 int n = score.length;
4 PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> score[b] - score[a]);
5 for (int i = 0; i < n; i++) {
6 heap.offer(i);
7 }
8 String[] medals = {"Gold Medal", "Silver Medal", "Bronze Medal"};
9 String[] answer = new String[n];
10 int place = 1;
11 while (!heap.isEmpty()) {
12 int i = heap.poll();
13 answer[i] = place <= 3 ? medals[place - 1] : String.valueOf(place);
14 place++;
15 }
16 return answer;
17 }
18}1class Solution {
2public:
3 vector<string> findRelativeRanks(vector<int>& score) {
4 int n = score.size();
5 priority_queue<pair<int, int>> heap;
6 for (int i = 0; i < n; i++) {
7 heap.push({score[i], i});
8 }
9 vector<string> medals = {"Gold Medal", "Silver Medal", "Bronze Medal"};
10 vector<string> answer(n);
11 int place = 1;
12 while (!heap.empty()) {
13 int i = heap.top().second;
14 heap.pop();
15 answer[i] = place <= 3 ? medals[place - 1] : to_string(place);
16 place++;
17 }
18 return answer;
19 }
20};Time and space complexity
O(n log n)
Building the heap is O(n) and each of the n pops costs O(log n).
O(n)
The heap holds n (score, index) pairs and the answer holds n strings.
Other approaches
Sort indices by score (time O(n log n), space O(n))
Sort the list of indices 0..n-1 by score descending, then walk it: position k in the sorted list is place k + 1. Same complexity and often simpler in languages without a built-in heap.
Bucket by score (time O(n + M) with M = max score, space O(M))
Scores are at most 10^6, so an array indexed by score can store which athlete has it. Walk the array from the top down to assign places. Linear in the score range rather than n.
Common mistakes
- Returning ranks in sorted order instead of input order. The rank must be written at the athlete's own index.
- Using a min-heap without negating the score in Python, which pops the lowest score first.
- Off-by-one on places: the first pop is place 1 (Gold Medal), not place 0.
- Writing "4th" or an integer instead of the plain string "4".
Frequently asked questions
Why store the index in the heap?
Popping gives the score order, but the answer is indexed by athlete. The stored index tells us where to write each rank.
Is a heap better than sorting here?
Not asymptotically. Both are O(n log n). The heap form matches how the problem reads (always take the best remaining athlete) and extends to cases where only the top k ranks are needed.
What if scores could tie?
The problem guarantees unique scores. With ties you would have to decide whether tied athletes share a place, which would change the assignment step.