File: relative-ranks/solution.py

Date: 2026-06-06

Time: 18:43

relative-ranks/solution.py

Purpose

This file solves LeetCode 506 — Relative Ranks. Given a list of unique athlete scores, it returns a list of rank labels in the same positional order. The top three get medal names; everyone else gets their numeric rank as a string.

Key Components

findrelativeranks(score: list[int]) -> list[str] — The sole function. Contract:

Patterns

Argsort idiom: sorted(range(n), key=lambda i: score[i], reverse=True) produces a permutation of indices ordered by descending score. This is Python's equivalent of NumPy's argsort — it avoids creating tuples of (score, index) and unpacking them later. The result ranked[k] answers "which original index has rank k+1?"

Pre-allocated result array: result = [""] * n is filled out of order via the index mapping, rather than building the result sequentially. This is the standard pattern when you need to write results back to original positions after sorting.

Dependencies

Flow

1. Compute n = len(score).

2. Build ranked: a list of indices [0, 1, ..., n-1] sorted so that score[ranked[0]] is the largest, score[ranked[1]] is second largest, etc.

3. Allocate result of length n, all empty strings.

4. Iterate place (0-indexed rank) and idx (original position): assign the medal string or numeric rank string to result[idx].

5. Return result.

Time complexity: O(n log n) from the sort. Space: O(n) for the ranked and result arrays.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints: 1 <= n <= 10^4, all scores unique and non-negative. Empty list input would produce an empty result (the loop body never executes). No exceptions are raised or caught.

Topics to Explore

Beliefs