progress

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

Counting Sort

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

easy ▶ boss game: The Tally 2 levels ~20 min

Level 1 Counting Sort

The Tally lines up a million monsters, weakest first, without comparing any two. Each has a power level from 1 to k, and k is small.

Write sort_powers(powers: list[int], k: int) -> list[int] that returns a new sorted list (don't change powers).

sort_powers([3, 1, 4, 1, 5, 9, 2, 6, 5, 3], 10)   # [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
sort_powers([2, 2, 1], 2)                          # [1, 2, 2]
sort_powers([7], 10)                               # [7]
sort_powers([], 5)                                 # []
  • len(powers) <= 10^6, 1 <= k <= 10^5. Don't use sorted, list.sort, heapq or bisect (the tests check).
  • ⭐ Bonus: a speed test with a million monsters earns a star in O(n + k).
Show hint

one counter per level, one walk over the army. The counters already describe the sorted army.

Level 2 unlocks when level 1 passes.

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