Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
1st place athlete's rank is "Gold Medal".2nd place athlete's rank is "Silver Medal".3rd place athlete's rank is "Bronze Medal".4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").Return an array answer of size n where answer[i] is the rank of the ith athlete.
Example 1:
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].
Example 2:
Input: score = [10,3,8,9,4] Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
Constraints:
n == score.length1 <= n <= 1040 <= score[i] <= 106score are unique.Problem summary: 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. The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank: The 1st place athlete's rank is "Gold Medal". The 2nd place athlete's rank is "Silver Medal". The 3rd place athlete's rank is "Bronze Medal". For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x"). Return an array answer of size n where answer[i] is the rank of the ith athlete.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[5,4,3,2,1]
[10,3,8,9,4]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #506: Relative Ranks
class Solution {
public String[] findRelativeRanks(int[] score) {
int n = score.length;
Integer[] idx = new Integer[n];
Arrays.setAll(idx, i -> i);
Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]);
String[] ans = new String[n];
String[] top3 = new String[] {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < n; ++i) {
ans[idx[i]] = i < 3 ? top3[i] : String.valueOf(i + 1);
}
return ans;
}
}
// Accepted solution for LeetCode #506: Relative Ranks
func findRelativeRanks(score []int) []string {
n := len(score)
idx := make([][]int, n)
for i := 0; i < n; i++ {
idx[i] = []int{score[i], i}
}
sort.Slice(idx, func(i1, i2 int) bool {
return idx[i1][0] > idx[i2][0]
})
ans := make([]string, n)
top3 := []string{"Gold Medal", "Silver Medal", "Bronze Medal"}
for i := 0; i < n; i++ {
if i < 3 {
ans[idx[i][1]] = top3[i]
} else {
ans[idx[i][1]] = strconv.Itoa(i + 1)
}
}
return ans
}
# Accepted solution for LeetCode #506: Relative Ranks
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
// Accepted solution for LeetCode #506: Relative Ranks
struct Solution;
#[derive(Debug, PartialEq, Eq, Clone)]
struct Athlete {
index: usize,
score: i32,
rank: String,
}
impl Solution {
fn find_relative_ranks(nums: Vec<i32>) -> Vec<String> {
let n = nums.len();
let mut a: Vec<Athlete> = vec![];
for i in 0..n {
a.push(Athlete {
index: i,
score: nums[i],
rank: "".to_string(),
});
}
a.sort_unstable_by(|a, b| b.score.cmp(&a.score));
for i in 0..n {
a[i].rank = match i {
0 => "Gold Medal".to_string(),
1 => "Silver Medal".to_string(),
2 => "Bronze Medal".to_string(),
_ => format!("{}", i + 1),
}
}
a.sort_unstable_by(|a, b| a.index.cmp(&b.index));
a.into_iter().map(|a| a.rank).collect()
}
}
#[test]
fn test() {
let nums = vec![5, 4, 3, 2, 1];
let res = vec!["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"];
assert_eq!(Solution::find_relative_ranks(nums), res);
}
// Accepted solution for LeetCode #506: Relative Ranks
function findRelativeRanks(score: number[]): string[] {
const n = score.length;
const idx = Array.from({ length: n }, (_, i) => i);
idx.sort((a, b) => score[b] - score[a]);
const top3 = ['Gold Medal', 'Silver Medal', 'Bronze Medal'];
const ans: string[] = Array(n);
for (let i = 0; i < n; i++) {
if (i < 3) {
ans[idx[i]] = top3[i];
} else {
ans[idx[i]] = (i + 1).toString();
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.