Unstable Sort Assumption
Problem
A leaderboard must list players by score, highest first, and break ties in favour of whoever submitted earlier. The engineer who wrote it knew that Python's sort is stable and reasoned "sort by score first, then sort by time to settle the ties":
def rank(players: list[dict]) -> list[dict]:
"""Highest score first; ties go to the earliest submission."""
players.sort(key=lambda p: p["score"], reverse=True)
players.sort(key=lambda p: p["submitted_at"])
return playersSymptom: the leaderboard is ordered by submission time, with scores apparently ignored. A separate concern raised in review: the same logic was ported to a C++ service using std::sort, and there the output is correct on some inputs and subtly wrong on others. Explain both, and fix the Python.
Examples
- Input
[("ann", 90, t=3), ("bob", 95, t=1), ("cy", 90, t=2)]→ expectedbob, cy, ann(95 first, then the two 90s withcyearlier). Actual:bob, cy, annagain, but only by luck, because here time order happens to agree with the intended order. - Input
[("ann", 90, t=1), ("bob", 95, t=2)]→ expectedbob, ann. Actual:ann, bob. The second sort reordered by time and destroyed the score ordering. - Ties only,
[("ann", 90, t=2), ("bob", 90, t=1)]→ expected and actualbob, ann. This is the case the engineer tested, which is why it looked correct.
Hints
- After the second
sort, which key determines the overall order, and which key only matters within groups of equal values? - Stability means: elements that compare equal keep their relative input order. Which sort here is looking at "equal" elements, and what is their input order at that point?
- Two ways to get a mixed-direction ordering in one sort: negate a numeric key, or run stable sorts from the least significant key to the most significant.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.