Magicsheet logo

Relative Ranks

Easy
100%
Updated 6/1/2025

Relative Ranks

What is this problem about?

The Relative Ranks problem gives you a list of athlete scores and asks you to assign ranks: 1st place → "Gold Medal", 2nd → "Silver Medal", 3rd → "Bronze Medal", others → their rank number as a string. This easy coding problem sorts with index tracking. The array, sorting, and heap interview pattern is demonstrated.

Why is this asked in interviews?

Electronic Arts, Amazon, Google, and Bloomberg ask this as a quick sorting with mapping problem. It validates sorted-index tracking and special-case rank labeling.

Algorithmic pattern used

Sort with original index tracking. Create pairs (score, index). Sort descending by score. For each position in sorted order: assign the appropriate label ("Gold Medal", "Silver Medal", "Bronze Medal", or rank number string) to result[original_index].

Example explanation

score=[5,4,3,2,1]. Sorted: [(5,0),(4,1),(3,2),(2,3),(1,4)].

  • Rank 1 (5,index0): result[0]="Gold Medal".
  • Rank 2 (4,index1): result[1]="Silver Medal".
  • Rank 3 (3,index2): result[2]="Bronze Medal".
  • Rank 4 (2,index3): result[3]="4".
  • Rank 5 (1,index4): result[4]="5". Result: ["Gold Medal","Silver Medal","Bronze Medal","4","5"].

Common mistakes candidates make

  • Sorting the original array and losing original indices.
  • Off-by-one in rank string (rank starts at 1, not 0).
  • Forgetting to handle top-3 as medal names.
  • Using integer rank instead of string for positions > 3.

Interview preparation tip

Relative Ranks demonstrates the "sort with index" pattern: enumerate, sort by value, assign to original positions. Always preserve indices when the output must match original array order. Practice this in: "assign grades," "rank products," "medal ceremony simulation." The special-case first 3 ranks require simple conditional handling.

Similar Questions