progress

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

Sort an Array

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 .

Write sort_numbers(nums: list[int]) -> list[int] that returns the numbers in ascending order. You may reorder nums itself or build a new list.

The point is to write the sorting yourself: don't call sorted, list.sort, heapq or any other library routine that sorts or keeps things in order for you. (The Python tests check for these calls.)

sort_numbers([5, 2, 3, 1])         # [1, 2, 3, 5]
sort_numbers([5, 1, 1, 2, 0, 0])   # [0, 0, 1, 1, 2, 5]
sort_numbers([-4, 10, -4])         # [-4, -4, 10]
sort_numbers([])                   # []

Constraints: 0 <= len(nums) <= 10^5, values in [-10^9, 10^9].

⭐ Bonus: speed tests with 100,000 values (random, already sorted, reversed, all equal) earn a star for O(n log n) in every case. Anything O(n²) on some input shape (swapping neighbours, inserting into place, splitting around the first element) still passes, just without the star.

Show hint

Two lists that are already sorted can be combined into one sorted list in a single pass, by repeatedly taking the smaller of their two front items. How could you get two sorted halves to combine?

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