Leetcode #506: Relative Ranks
In this guide, we solve Leetcode #506 Relative Ranks in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Python Solution
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n = len(score)
idx = list(range(n))
idx.sort(key=lambda x: -score[x])
top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"]
ans = [None] * n
for i, j in enumerate(idx):
ans[j] = top3[i] if i < 3 else str(i + 1)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.