Essential Data Structures home
Heap
A tree where the smallest (or largest) item is always on top, so the next most urgent thing is always one step away. It is the engine inside every priority queue.
What it is
A heap is a tree with two rules. First, it is a complete binary tree: every level is filled from left to right, except possibly the last, which fills from the left. Second, it obeys the heap property: in a min-heap, every parent is smaller than or equal to its children, so the smallest item is always at the root. In a max-heap, the rule is flipped, and the largest item is at the root.
A heap is not sorted. The children of a node can be in any order relative to each other, and the leaves hold the largest values in no particular order. Only the root is guaranteed to be the extreme value. That loose ordering is the point: a heap does less work than a sorted structure, because it only promises the next most urgent item, not the full order.
Because the tree is complete, it can be stored in a plain array with no pointers. The root is at index 0. For a node at index i, its children sit at 2i + 1 and 2i + 2, and its parent sits at (i - 1) / 2, rounded down. The tree shape is implied by the positions, so a heap is usually just an array with a few rules for moving items up and down.
How it works
Insert puts the new item in the first free slot at the end of the array, then bubbles it up. While the new item is smaller than its parent (in a min-heap), swap it with the parent and repeat. The item climbs at most the height of the tree, so insert is O(log n).
Extracting the minimum takes the root, moves the last item in the array into the root position, and then sifts it down. While the item is larger than its smallest child, swap it with that child and repeat. The item sinks at most the height of the tree, so extract is O(log n). Peeking at the root, without removing it, is O(1), since the smallest item is already there.
Building a heap from an unsorted array is faster than inserting one item at a time. Instead of n inserts at O(log n) each, heapify works from the bottom up: start at the last parent and sift each node down, so the lower levels do almost no work. The total cost is O(n), not O(n log n). That is the trick behind heap sort, which heapifies the array and then repeatedly extracts the minimum into the freed slots at the end.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Peek at minimum or maximum | O(1) | O(1) |
| Insert | O(log n) | O(log n) |
| Extract minimum or maximum | O(log n) | O(log n) |
| Delete an arbitrary item | O(log n) | O(log n) |
| Search by value | O(n) | O(n) |
| Build heap from n items (heapify) | O(n) | O(n) |
| Merge two heaps | O(n) | O(n) |
n is the number of items. Delete of an arbitrary item is O(log n) once you know its position; finding it by value still costs O(n). Merging two heaps means concatenating their arrays and heapifying, which is O(n) for the combined size.
When to use it, and when not to
Use a heap when you only ever need the next most urgent item, and you need it again and again. That is the shape of a priority queue: tasks by deadline, events by time, patients by triage, and the next node to visit in Dijkstra's shortest path algorithm. A heap is also the right tool for keeping the k largest or smallest items from a stream, and for heap sort when the sort must run in place with O(1) extra space.
Do not use a heap when you need to search for an arbitrary value, because that is a linear scan. Do not use it when the items must stay in full sorted order, because a heap is not sorted; a balanced search tree gives you order and search for the same logarithmic cost. And do not use it when the priority of an item changes often in place, unless you also keep a map from item to position, because finding the item to update costs O(n) without one.
Where you meet it
Heaps run the schedulers. Operating systems pick the next process to run from a priority queue, network routers forward the most urgent packet first, and simulations pull the next event from a heap ordered by time. Dijkstra's algorithm and Prim's algorithm for minimum spanning trees both lean on a heap to fetch the cheapest next node. Python's heapq module is a heap in the standard library, and it is the usual way to build a priority queue or to pull the n smallest items from a list without sorting the whole thing.
In Python
import heapq
tasks = [] # a min-heap of (priority, name) pairs
heapq.heappush(tasks, (3, "write report"))
heapq.heappush(tasks, (1, "fix outage"))
heapq.heappush(tasks, (2, "review pull request"))
print(tasks[0]) # (1, 'fix outage'), the most urgent, O(1)
print(heapq.heappop(tasks)) # (1, 'fix outage'), removed in O(log n)
print(heapq.heappop(tasks)) # (2, 'review pull request')
scores = [9, 4, 7, 1, 5, 3]
heapq.heapify(scores) # turn a list into a heap in O(n)
print(scores) # [1, 4, 3, 9, 5, 7], heap order, not sorted
print(heapq.nsmallest(3, [9, 4, 7, 1, 5, 3])) # [1, 3, 4]
In short: a heap keeps only one promise, that the smallest (or largest) item is on top. That single promise is cheap to keep, O(log n) per change, and it is exactly what a priority queue needs.
Sources
- Heap (data structure), Wikipedia
- Python docs, heapq (heap queue algorithm)
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 6