Heaps and priority queues
A priority queue always gives you the item with the highest priority next, not the one that arrived first: the most urgent hospital patient, the next timer to fire, the cheapest path to explore. It's implemented with a heap, a tree-shaped structure stored in a plain array that makes both "add" and "take the best" O(log n).
The heap property
In a min-heap, every parent is smaller than (or equal to) its children, so the minimum is always at the root. The tree is kept complete (filled level by level), which lets it live in a list without pointers:
1 index: 0 1 2 3 4 5 6
/ \ value: [1, 3, 2, 7, 4, 5, 6]
3 2
/ \ / \ children of i: 2i + 1 and 2i + 2
7 4 5 6 parent of i: (i - 1) // 2Building one from scratch
Height is log₂ n, so sifting up or down takes at most O(log n) swaps.
Python's heapq
Use the standard library. heapq works on an ordinary list as a min-heap:
For a max-heap, push negated keys: heapq.heappush(h, (-score, name)).
Top-k with a heap
To find the k largest of n items, keep a min-heap of size k: the smallest of your current top k sits at the root, ready to be replaced. That's O(n log k) time and O(k) memory, which works even for a stream too big to sort:
Merging k sorted lists
Each list's next item goes into a heap; repeatedly take the smallest. O(n log k) for n total items, the basis of external sorting and of databases merging sorted files:
Running median with two heaps
Keep the lower half in a max-heap and the upper half in a min-heap, balanced in size. The median is always at one or both roots:
Scheduling with a heap
Rooms needed for a set of meetings: sort by start time, and keep a min-heap of end times of meetings in progress:
Operating system schedulers, timer wheels, event simulations and Dijkstra's shortest-path algorithm (in the advanced graphs lesson) all run on heaps.
Heap operations at a glance
| Operation | Cost |
|---|---|
| Peek at the min | O(1) |
| Push | O(log n) |
| Pop the min | O(log n) |
Build from n items (heapify) |
O(n) |
| Search for an arbitrary item | O(n): heaps aren't sorted |
Practice
- Find the k-th largest element in a list using a heap of size k.
- Sort a "nearly sorted" list where each item is at most k places from its final position, in O(n log k).
- Simulate a hospital queue: patients have a severity (1 = most urgent) and arrival order; urgent first, then first come, first served.
1.Where is the smallest item in a min-heap?
2.What does pushing onto a heap of n items cost?
3.How do you find the 10 largest numbers in a stream of a billion numbers with little memory?