Skip to content
Problem 506 · LeetCode 506(opens in a new tab)

Relative Ranks

EasyArrays

score[i] is the score of athlete i in a contest, and no two athletes share a score. The highest score finishes 1st, the next highest 2nd, and so on.

Each athlete gets a rank from their finishing place: 1st is "Gold Medal", 2nd is "Silver Medal", 3rd is "Bronze Medal", and every place after that is just its number as a string, like "4". Return the ranks in the same order as score.

Example 1

Input:  score = [12, 30, 7, 25]
Output: ["Bronze Medal", "Gold Medal", "4", "Silver Medal"]
Why:    the finishing order is 30, 25, 12, 7
2 more examples and the constraints

Example 2

Input:  score = [8, 6, 9, 3, 1, 5]
Output: ["Silver Medal", "Bronze Medal", "Gold Medal", "5", "6", "4"]
Why:    9 wins, then 8 and 6; 5, 3 and 1 place 4th to 6th

Example 3

Input:  score = [42]
Output: ["Gold Medal"]
Why:    a lone athlete wins

Constraints

  • 1 ≤ score.length ≤ 10,000
  • 0 ≤ score[i] ≤ 1,000,000
  • All scores are different.

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count higher scoresO(n²)
  2. Sort the indicesO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 athletesVerdict
Count higher scoresO(n²)
Correct, rescans everything
Sort the indicesO(n log n)
Best; one sort

n = number of athletes.

Edge cases to test

  • One athlete. [42] gives ["Gold Medal"].
  • Two athletes. [1, 2] gives ["Silver Medal", "Gold Medal"]; there is no bronze.
  • A score of 0. 0 is a valid score and simply ranks below every positive one.
  • Already sorted. Descending input gives the medals first and then "4", "5", and so on in order.
  • Places past 3. The 10th place is "10", a string, not the number 10.

Common mistakes

  • Sorting the scores and losing which athlete had which score.
  • Sorting from lowest to highest, so the weakest athlete gets gold.
  • Writing place instead of place + 1 for the numbered ranks, so 4th shows as "3".

How to talk through it

  1. 1Clarify. Are scores unique? Is the answer in the original order, with places past 3 as strings?
  2. 2Give the brute force. For each athlete count the higher scores: O(n²).
  3. 3Sort indices, not values. Sorting indices by score keeps the link back to each athlete.
  4. 4Write ranks back. Walk the order and fill ans[index] with a medal or place + 1.
  5. 5Test out loud. Run one athlete, two athletes and a case past 3rd place.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?