LeetCode #506 Easy

Relative Ranks

Relative Ranks is LeetCode 506 (Easy). score[i] is the score of athlete i, and all scores are different. The highest score places 1st, the next places 2nd, and so on.

  • Places 1, 2 and 3 get the labels "Gold Medal", "Silver Medal" and "Bronze Medal".
  • Every later place gets its number as a string, such as "4".

Return the labels in the same order as score: answer[i] is athlete i's label.

Constraints
  • n == score.length
  • 1 <= n <= 10^4
  • 0 <= score[i] <= 10^6
  • All the values in score are unique.
heapsortingarray
Open on LeetCode ↗
02

Intuition

A place comes from sorted order, but the answer must stay in input order. Sorting score itself breaks that link: after sorting you know the 2nd-best score but not whose it was.

So sort the athlete numbers instead of the scores, using each athlete's score as the sort key, highest first. Walking that list hands out places 1, 2, 3, … in order, and each label is written into answer[athlete]. The answer is filled out of order but read in input order, which is exactly what the problem asks for.

How to spot this pattern

"Rank every item but report the ranks in the original order" means sorting indices by value and writing results back through those indices. The same move solves Rank Transform of an Array and any "replace each element by its rank" task.

03

Approach

Try it first

Before reading on, work out how you would still know whose score is whose after sorting. Then decide where in the answer each label must go. Aim for O(n log n).

1

Sort the athlete numbers by score

Build order = sorted(range(n), key=lambda i: -score[i]). The minus sign sorts highest first, and because the list holds athlete numbers, each entry still says whose score it is.

2

Label each place

Walk order with its position place, counting from 0. Places 0, 1 and 2 take "Gold Medal", "Silver Medal" and "Bronze Medal" from a small list, and every later place takes its place number as a string, str(place + 1).

3

Write the label back to its athlete

Store the label in answer[order[place]]. That slot is the athlete's original position, so when the loop ends the answer lines up with score without any second pass.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findRelativeRanks(self, score):
▶3 order = sorted(range(len(score)), key=lambda i: -score[i])
▶4 medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
▶5 answer = [""] * len(score)
▶6 for place, i in enumerate(order):
▶7 answer[i] = medals[place] if place < 3 else str(place + 1)
▶8 return answer
score10athlete 03athlete 18athlete 29athlete 34athlete 4by scoreanswerathlete 0athlete 1athlete 2athlete 3athlete 45 athletes, scores in input order
score[10, 3, 8, 9, 4]all different
Each athlete's rank depends on every other score, but the answer must list the athletes in their original order. So the plan is to sort a list of athlete numbers, not the scores themselves, and keep the scores where they are.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerathlete 0athlete 1athlete 2athlete 3athlete 4sort athletes by score, highest first
order[0, 3, 2, 4, 1]athlete numbers
Sorting the athlete numbers by score, highest first, gives the finishing order: position 1 is the winner. Each sorted entry still says which athlete it belongs to, which is what lets the label go back to the right slot.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 0athlete 1athlete 2athlete 3athlete 41st place is athlete 0 → Gold Medal
place1score 10
answer[0]"Gold Medal"
Place 1 gets the label "Gold Medal", spelled exactly like that, space included. It is written into slot 0, the athlete's original position, so the answer fills out of order but reads in input order.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 0athlete 1athlete 2Silverathlete 3athlete 42nd place is athlete 3 → Silver Medal
place2score 9
answer[3]"Silver Medal"
Place 2 gets the label "Silver Medal", spelled exactly like that, space included. It is written into slot 3, the athlete's original position, so the answer fills out of order but reads in input order.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 0athlete 1Bronzeathlete 2Silverathlete 3athlete 43rd place is athlete 2 → Bronze Medal
place3score 8
answer[2]"Bronze Medal"
Place 3 gets the label "Bronze Medal", spelled exactly like that, space included. It is written into slot 2, the athlete's original position, so the answer fills out of order but reads in input order.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 0athlete 1Bronzeathlete 2Silverathlete 34athlete 44th place is athlete 4 → "4"
place4score 4
answer[4]"4"
From 4th place on, the label is just the place number as a string: "4". The loop index starts at 0, so the place is the index plus 1. It is written into slot 4, the athlete's original position, so the answer fills out of order but reads in input order.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 05athlete 1Bronzeathlete 2Silverathlete 34athlete 45th place is athlete 1 → "5"
place5score 3
answer[1]"5"
From 4th place on, the label is just the place number as a string: "5". The loop index starts at 0, so the place is the index plus 1. It is written into slot 1, the athlete's original position, so the answer fills out of order but reads in input order.
score10athlete 03athlete 18athlete 29athlete 34athlete 4by score101stathlete 092ndathlete 383rdathlete 244thathlete 435thathlete 1answerGoldathlete 05athlete 1Bronzeathlete 2Silverathlete 34athlete 4all 5 labelled → return the answer
result["Gold Medal", "5", "Bronze Medal", "Silver Medal", "4"]
Every slot is filled. Reading the answer left to right gives each athlete's label in the order the scores were given.
05

Common pitfalls

Sorting the scores instead of the athletes

✗ Wrong
ranked = sorted(score, reverse=True)
for place, s in enumerate(ranked):
    answer[place] = label(place)
✓ Right
order = sorted(range(n), key=lambda i: -score[i])
for place, i in enumerate(order):
    answer[i] = label(place)

Writing to answer[place] lists the labels in finishing order, not athlete order. For [10,3,8,9,4] it returns ["Gold Medal","Silver Medal","Bronze Medal","4","5"], but athlete 1 scored 3 and should get "5".

Off by one on the place number

✗ Wrong
answer[i] = str(place)
✓ Right
answer[i] = str(place + 1)

enumerate starts at 0, but places start at 1. The three medals hide the mistake, so it first shows on [5,4,3,2,1], where the 4th athlete comes out as "3".

06

Edge cases

Fewer than three athletes

With [7,9] only Gold and Silver are handed out: ["Silver Medal","Gold Medal"]. The loop stops after two places, so no extra check is needed.

07

Complexity

Time
O(n log n)
Space
O(n)
Sorting the n athlete numbers dominates; the labelling pass is O(n). The sorted list and the answer each hold n entries.
08

Relative Ranks FAQ

Can it be solved with a heap?

Yes. Push (-score[i], i) for every athlete into a min-heap and pop n times; the k-th pop is place k. It costs the same O(n log n) as sorting, so it only helps if you want to stop after the first few places.

Is there a faster way than sorting?

Scores are at most 10^6, so you can mark each score in an array of size 10^6 + 1 and scan it from the top, handing out places as you meet marked scores. That is O(n + max score) time but needs a million-slot array, so sorting is usually the better fit.