synopsis · Trees & graphs · chapter 24
Heaps & Priority Queues
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A heap is a complete binary tree in an array: every parent ≤ its children (min-heap). The min sits at index 0; children of i are 2i + 1 and 2i + 2.
- cost
peekO(1) ·offer/pollO(log n) · build from n values O(n) ·remove(x)/containsO(n) · heap sort O(n log n) in O(1) space. - use it when
You need the current min/max while items keep arriving: top-k, k closest, running median, merge k sorted lists, greedy "take the best next".
- template
k largest: min-heap,
pq.offer(x); if (pq.size() > k) pq.poll();— the root is the k-th largest. k smallest: the same with a max-heap. - template
Median: max-heap
low+ min-heaphigh. Offer to low, move low's max to high, move it back if high is bigger. Median = the tops. - template
K-way merge: one cursor per sorted list in a min-heap. Poll the smallest, offer that list's next. O(N log k) time, O(k) space.
- trap
Printing or iterating a
PriorityQueueis NOT sorted — only repeatedpoll()returns values in order. - trap
(a, b) -> a - boverflows for far-apart values and silently mis-orders the heap. UseInteger.compareorComparator.comparingInt. - pro tip
No decrease-key in Java: offer a new entry and skip stale ones when you poll them (lazy deletion), as Dijkstra does.
Shaky on a card? Open the chapter or flip its recall cards.