Problem solving · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Unstable Sort Assumption

mediumdebugging

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 players

Symptom: 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)] → expected bob, cy, ann (95 first, then the two 90s with cy earlier). Actual: bob, cy, ann again, but only by luck, because here time order happens to agree with the intended order.
  • Input [("ann", 90, t=1), ("bob", 95, t=2)] → expected bob, 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 actual bob, ann. This is the case the engineer tested, which is why it looked correct.

Hints

  1. After the second sort, which key determines the overall order, and which key only matters within groups of equal values?
  2. 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?
  3. 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