Relative Ranks

Solution walkthrough for relative ranks with code and practical use cases.

Easy1 min read
Lookup / Frequency / MatchingHash Map

What This Problem Is Asking

In one sentence

Identify the core operation required by the prompt and produce the expected output efficiently.

Full problem statement

Relative Ranks

You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All scores are unique.

Return an array answer of size n where answer[i] is the rank string of the ith athlete:

- Rank "Gold Medal" for the 1st place score - Rank "Silver Medal" for the 2nd place score - Rank "Bronze Medal" for the 3rd place score - For the 4th place and below, rank is the place number as a string ("4", "5", …)

The answer array must preserve the original order of athletes by index.

Recognition Clues

Signals that this pattern likely applies.

  • You need fast lookup while iterating once.
  • You are asked for indices, pairs, or direct matches.

Why This Pattern Fits

This pattern minimizes repeated scanning and keeps lookup decisions close to the traversal.

Daily usefulness: Useful in data validation, filtering, and UI state transformations encountered in daily product work.

Interview usefulness: This pattern appears frequently in screening rounds due to its clarity and optimization tradeoffs.

Real-world relevance: Maps to production concerns like deduplication, lookup acceleration, and ranking support.

Code Snippets

Swift

Visual Demo

Leaderboard ranks

Players start in arbitrary order. Press the button to sort by score and assign Gold, Silver, Bronze, and numeric ranks—the same labels findRelativeRanks returns for each score position.

Registration order — ranks hidden.

PlayerScore
nova_k92
pixelFox78
orbit95
cache_me88
lambda_lily71

Practical Use Cases

  • Resolve complementary value lookups in near real-time APIs.
  • Detect matching pairs in transactional or telemetry streams.
  • Use hash-map pairing logic in data validation pipelines.

Demo Ideas

Interactive ways to teach this algorithm.

  • Animate lookup table growth while scanning inputs.
  • Visualize when candidate matches become valid outputs.

Related Problems