Overview
Curated: · Written: · Reviewed:
Heaps / Priority Queues
In one line
A binary heap is an array-backed complete tree that keeps the minimum (or maximum) at the root, so peek is O(1) and push or pop is O(log n). Reach for it when you repeatedly need the most extreme remaining item from a set that keeps changing.
Key definitions
- Heap invariant: each parent is at least as extreme as its children (min-heap: parent <= children). Siblings and the array as a whole are not ordered.
- Sift-up: after a push, move the new element up from the end until the invariant holds.
- Sift-down: after a pop, move the last element down from the root, swapping with the smaller child.
- Lazy deletion: mark or skip stale entries instead of removing them. The heap then grows with insertions, not live items.
- Decrease-key: lowering a key in place. A binary heap needs an index map for it; Dijkstra usually pushes a new entry instead.
- Tiebreaker: a monotonic sequence number that makes equal priorities pop FIFO and keeps payloads out of comparisons.
Formulas and complexity
Dijkstra with a binary heap:
Fibonacci heaps give amortised O(1) decrease-key and O(E + V log V) Dijkstra, but are rarely faster in practice.
How it works
- Zero-based layout: children of i are 2i+1 and 2i+2, parent is (i-1)//2. Fix the convention once and test the invariant over the array.
- Push appends at the end and sifts up. Pop takes the root, moves the last element to the root, and sifts down.
- Heapify sifts down from the last internal node to the root. The sum of node heights is O(n), so the build is linear.
- Only the root is guaranteed. The underlying list is not sorted, so
h[3]is not the fourth-smallest.
When to use and when not to
| Need | Heap fit | Better choice |
|---|---|---|
| Repeated min or max over a changing set | Yes | none |
| Fixed set, one sorted output | No | sort once |
| Membership or arbitrary removal | No, O(n) | hash set or balanced tree |
| Top-k of a stream | Yes, size-k min-heap, O(n log k) | quickselect if order is not needed |
| Running median | Two heaps | none |
| Ordered iteration | No | balanced tree |
Traps interviewers probe
- Max-heap for top-k. Fix: keep a min-heap of size k so the weakest candidate sits at the root, and pop when size exceeds k.
- Reading
h[3]as the fourth-smallest. Fix: onlyh[0]is guaranteed. Drain or sort for anything beyond the root. - Negating
Integer.MIN_VALUEin Java. The negation overflows back toMIN_VALUE, so that job becomes the most urgent in a min-heap. Fix: useCollections.reverseOrder()as the comparator instead of negation. - Pushing
(priority, payload)tuples. A priority tie compares payloads and raisesTypeError. Fix: insert a unique sequence number as the second element. - Building by repeated push when the whole list is available. That costs O(n log n). Fix: call
heapify, which is O(n).
Interview tips
Open with the guarantee: "A heap guarantees only that the extremum is at the root. That weakness is why push and pop are O(log n) and peek is O(1)."
Expect these follow-ups:
- Why binary heaps lack decrease-key, and what Dijkstra does instead (push a new entry, skip stale ones, memory O(E)).
- Why heaps are not stable, and how a sequence number fixes it.
- Why the two-heap median rebalances after every insertion.
- Why heapsort, at O(n log n) worst case and O(1) extra space, rarely beats the library sort in practice.
- Why a heap starves low-priority work, and why oldest-item age reveals it when depth does not.
30-second outline: state the invariant and the root guarantee; give the array layout and the push and pop costs; name the problem shape (repeated extremum over a changing set); give one trap with its fix; say what you would measure before changing the structure.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.