Relative Ranks — Solution in Python, Java & C++
Relative Ranks solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and sorting.
Relative Ranks is an easy coding problem on arrays, sorting and heap.
- Difficulty: Easy
- Topics: Arrays, Sorting, Heap
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given the scores of n athletes as an array of numeric strings (all unique). Ranks go to the highest scores: the top three earn "Gold Medal", "Silver Medal", "Bronze Medal"; everyone else gets their placement number as a string ("4", "5", …).
Return the rank of each athlete in the input order.
Example 1
Input: score = ["5","4","3","2","1"]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Example 2
Input: score = ["10","3","8","9","4"]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Constraints
1 <= score.length <= 250 <= score[i] <= 100 (unique)
Hints for Relative Ranks
Hint 1
Sort indices by score descending, then write ranks back into the original positions.
Hint 2
Convert scores to numbers before comparing — string comparison misorders "9" and "10".
How to solve Relative Ranks
Ranking is about order, but the answer must come back in input order. Sorting the scores themselves loses the connection to each athlete, so sort an array of indices instead, ordered by score descending. Position r in that sorted list tells you the athlete at that index finished r + 1-th.
Approach
- Convert each score string to a number.
- Build the index list
0, 1, ..., n-1and sort it by score descending. - Walk that sorted list. The athlete at sorted position
rhas rankr + 1. - Write the medal for
r = 0, 1, 2and the stringr + 1otherwise — writing it back at the athlete's original index. - Return the result array, which is already in input order.
Why it works
Sorting indices rather than values keeps each score attached to the athlete it belongs to, so writing the answer back at the original index restores the required output order for free. Because the scores are guaranteed unique, the descending sort is a strict total order and every rank is unambiguous.
Complexity
- Time —
O(n log n) - Space —
O(n)
Pitfalls
- Compare scores numerically. The input arrives as strings, and lexicographic comparison puts
"9"above"10". - Ranks are 1-based while sorted positions are 0-based — the non-medal answer is
r + 1. - Write results at the original index, not sequentially, or the output ends up in ranked order rather than input order.
- Fewer than three athletes is normal; the medal branch must not read past the end of the medal list.
Reference solution
Python
from typing import List
def findRelativeRanks(score: List[str]) -> List[str]:
nums = [int(s) for s in score]
order = sorted(range(len(nums)), key=lambda i: -nums[i])
medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
out = [""] * len(nums)
for rank, i in enumerate(order):
out[i] = medals[rank] if rank < 3 else str(rank + 1)
return outJava
public static String[] findRelativeRanks(String[] score) {
int n = score.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> Integer.parseInt(score[b]) - Integer.parseInt(score[a]));
String[] medals = {"Gold Medal", "Silver Medal", "Bronze Medal"};
String[] out = new String[n];
for (int rank = 0; rank < n; rank++) {
out[idx[rank]] = rank < 3 ? medals[rank] : String.valueOf(rank + 1);
}
return out;
}C++
vector<string> findRelativeRanks(vector<string>& score) {
int n = (int) score.size();
vector<int> idx(n);
for (int i = 0; i < n; i++) idx[i] = i;
sort(idx.begin(), idx.end(), [&score](int a, int b) {
return stoi(score[a]) > stoi(score[b]);
});
string medals[3] = {"Gold Medal", "Silver Medal", "Bronze Medal"};
vector<string> out(n);
for (int rank = 0; rank < n; rank++) {
out[idx[rank]] = rank < 3 ? medals[rank] : to_string(rank + 1);
}
return out;
}JavaScript
var findRelativeRanks = function(score) {
const order = score
.map(function(s, i) { return { s: parseInt(s, 10), i: i }; })
.sort(function(a, b) { return b.s - a.s; });
const medals = ["Gold Medal", "Silver Medal", "Bronze Medal"];
const out = new Array(score.length).fill("");
order.forEach(function(e, rank) {
out[e.i] = rank < 3 ? medals[rank] : String(rank + 1);
});
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Sorting Algorithms