Heaps and priority queues: always know the smallest
How a binary heap stores a complete tree in a plain array, why push and pop cost O(log n), and when a heap beats sorting.
In short
A heap keeps the smallest (min-heap) or largest (max-heap) item at the root, and every parent is ≤ its children. Reading the top is O(1); push and pop are O(log n). It's the data structure behind a priority queue.
A tree stored in an array
A heap is a complete binary tree (every level full except maybe the last, filled left to right), so it fits in an array with no pointers: the children of index i are 2i+1 and 2i+2, and its parent is (i−1)//2.
1def push(h, x):2 h.append(x)3 i = len(h) - 14 while i > 0 and h[(i - 1) // 2] > h[i]:5 h[(i - 1) // 2], h[i] = h[i], h[(i - 1) // 2]6 i = (i - 1) // 278def pop(h):9 top = h[0]10 h[0] = h[-1]; h.pop()11 i = 012 while True:13 c = smaller_child(h, i)14 if c is None or h[i] <= h[c]: break15 h[i], h[c] = h[c], h[i]16 i = c17 return top
Variables
- Push: add at the end, then sift up while smaller than the parent.
- Pop: take the root, move the last element to the root, then sift down, swapping with the smaller child.
- Both walk one root-to-leaf path: the height is log n, hence O(log n).
When to use a heap
| Need | Structure | Cost |
|---|---|---|
| Repeatedly the min or max of a changing set | Heap | O(log n) per op |
| Min or max of a fixed array, once | A single scan | O(n) |
| Everything in order | Sort | O(n log n) |
| Min and max, or any element by value | Balanced BST / sorted structure | O(log n) |
- Python:
heapqis a min-heap on a list. For a max-heap, push negated values. - Java:
PriorityQueueis a min-heap; passCollections.reverseOrder()for a max-heap. - TypeScript: no built-in; write a small class or use a library.
- Building a heap from n items is O(n) with heapify, cheaper than n pushes.
Key takeaways
- 01A heap is a complete tree in an array; parent (i−1)//2, children 2i+1 and 2i+2.
- 02Peek O(1); push and pop O(log n).
- 03Python's heapq is a min-heap: negate values for a max-heap.
- 04Use a heap when you repeatedly need the best remaining item.
Check your understanding
1 of 3
Cost of reading the smallest element of a min-heap?
Related topics
Top-K
To get the K largest, keep a min-heap of size K: its root is the weakest winner. For each number, if it beats the root, replace it. Cost: O(n log k) time, O(k) space.
8 min read →Traversals
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
9 min read →