Sort a leaderboard by score, then latency, then name with np.lexsort

Why it matters Multi-key sorting with explicit tie-breakers keeps leaderboards and ranked retrieval results stable and fair.

A model leaderboard sorts by score (higher first); ties go to the faster model (lower latency), and remaining ties to the alphabetically first name. np.lexsort does a multi-key sort in one call, but its key order trips people up.

Write leaderboard_order(scores, latency, names). All three are 1D arrays of length N (names are strings). Return the int array of indices that orders the leaderboard: score descending, then latency ascending, then name ascending.

Signaturedef leaderboard_order(scores, latency, names)

Example

scores [0.9, 0.8, 0.9], latency [120, 50, 80], names ['a', 'b', 'c'] gives [2, 0, 1].

Understand the idea

Sorting by several keys means: sort by the main key, and only use the next key when the main key ties. np.lexsort does this with a tuple of keys, but it reads them from the END: the last key is primary, the one before it breaks ties, and so on. It is stable, so full ties keep their input order.

Worked example: scores [0.9, 0.8, 0.9], latency [120, 50, 80]. Score descending puts items 0 and 2 (0.9) before item 1 (0.8). Items 0 and 2 tie, so latency decides: item 2 (80) before item 0 (120). Order [2, 0, 1].

Rule: np.lexsort((tie2, tie1, primary)). For descending numbers, use -key.

Leaderboards, ranked search results and deterministic top-k with tie-breaking use multi-key sorts.

Shapes and data flow

scores, latency, names (N,) -> order (N,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleleaderboard_order([0.9, 0.8, 0.9], [120, 50, 80], ['a', 'b', 'c'])
  • Sample 2: ties on score and latencyleaderboard_order([0.7, 0.7, 0.7, 0.9], [10, 10, 5, 99], ['zed', 'amy', 'kim', 'bob'])
  • Test 3: all different scoresleaderboard_order([0.1, 0.5, 0.3], [1, 1, 1], ['x', 'y', 'z'])