Relative Ranks (LeetCode 506): Solution and Explanation

Easy
Array
Sorting
Heap (priority queue)

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)

  1. Build a max-heap of (score[i], i) for every athlete. In Python, push (-score, i) into heapq.
  2. Set place = 1 and create answer with n empty slots.
  3. Pop the heap. The popped athlete i gets "Gold Medal", "Silver Medal" or "Bronze Medal" for places 1 to 3, and str(place) otherwise.
  4. Increment place and repeat until the heap is empty.

Step-by-step example

score = [5,4,3,2,1]
  1. Build the max-heap. Its root is 5 (athlete 0).
  2. Pop 5 (athlete 0): place 1, answer[0] = "Gold Medal".
  3. Pop 4 (athlete 1): place 2, answer[1] = "Silver Medal".
  4. Pop 3 (athlete 2): place 3, answer[2] = "Bronze Medal".
  5. 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 answer
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Building the heap is O(n) and each of the n pops costs O(log n).

Space

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.