Medium interview relevanceRoadmap: Advanced
TimeΘ(n log n) for distinct keys
SpaceO(1) when done in place

Why it costs this much

Building a heap takes O(n), then removing the extreme item n times costs O(log n) each.

Code

import heapq
def heap_sort(items):
    h = list(items)
    heapq.heapify(h)                                   # O(n)
    return [heapq.heappop(h) for _ in range(len(h))]   # n pops x O(log n)
# Textbook heapsort does the same work in place with O(1) extra space.

Common pitfalls

Heapsort is not stable and has poor cache behavior, so it is often slower than quicksort in practice.

Operation by operation

OperationBestAverageWorstSpace
HeapsortO(n log n) for distinct keysO(n log n)O(n log n)O(1)

Heapsort. In place. Not stable. Slower in practice than quicksort because of poor cache locality.

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