~/problems / Arrays & hashing / Sorting, custom keys, coordinate compression

Basics: leaderboard with a tuple sort key

easy basics ~10 min

Write leaderboard(results: list[tuple[str, int]]) -> list[str]. Each entry is (name, score). Return the names in leaderboard order:

  1. higher score first;
  2. on equal scores, names in alphabetical order (plain string comparison).
leaderboard([("mia", 70), ("ben", 90), ("ada", 70), ("zoe", 85)])
# ["ben", "zoe", "ada", "mia"]
  • 0 <= len(results) <= 10^5; scores can be negative; names are distinct lowercase words.
  • Don't change the results list you were given; return a new list.
Show hint

use one sorted(..., key=...) call whose key is a tuple, (-score, name): tuples compare field by field, and negating the score turns "descending" into "ascending".

Topic: Sorting, custom keys, coordinate compression. sorted(key=...), multi-key and stable sorts, cmp_to_key, compressing coordinates.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc