Medium interview relevanceRoadmap: Advanced
TimeO(n log n) worst case; O(n) on already-sorted input
SpaceO(n)

Why it costs this much

Timsort merges runs of already-ordered data, so nearly sorted input is fast and the worst case is still O(n log n).

Code

items.sort()                        # O(n log n) worst case, stable
items.sort(key=lambda p: p[1])      # key is computed once per element
ordered = sorted(items)             # returns a new list: O(n) extra space

Common pitfalls

Sorting costs O(n log n), which dominates any linear pass that follows. The key function runs once per element.

Operation by operation

OperationBestAverageWorstSpace
Built-in sort (Python sorted, list.sort)O(n)O(n log n)O(n log n)O(n)

Built-in sort (Python sorted, list.sort). Timsort. Stable. Runs of already-sorted data are detected. Java sorts objects with the same Timsort idea and primitives with dual-pivot quicksort. JavaScript Array.sort is stable since ES2019.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list