Heaps · Lesson
Heaps and priority queues, explained: top k, merging and every pattern
Learn heaps and priority queues: top k and kth largest, custom comparators, merging k sorted lists and two heaps, with templates in Java, Python, C++ and JS.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What a heap gives you
A heap (priority queue) always knows its smallest item. Peeking at it is O(1); adding an item or removing the smallest is O(log n). It does not keep everything sorted, only the best item on top, and that is exactly why it is cheaper than sorting again after every change.
Inside, it is a complete binary tree stored in an array: the children of index i sit at 2i + 1 and 2i + 2, and every parent is ≤ its children. A push goes at the end and swaps up past bigger parents; a pop moves the last item to the root and swaps it down. Each walk is the height of the tree, so log n steps.
Min heap or max heap?
- The k largest: keep a min heap of size k. The top is the weakest of your current best k, so it is the one to throw out when something better arrives. That costs O(n log k) and O(k) memory.
- Repeatedly take the biggest: a max heap. In Python, push
-x; in Java, passCollections.reverseOrder(); in C++,priority_queue<int>is already a max heap. - Order by several things at once: store tuples or arrays and write the comparator for the first key, then the tie-break.
- Merge k sorted sources: a min heap holding one item per source, plus where that item came from.
What a heap cannot do
A heap cannot find or delete an arbitrary item quickly. When items change or expire, use lazy deletion: leave the stale entry in the heap, and when it reaches the top, check it against the truth (a hash map) and throw it away if it is out of date. If you need the min, the max and deletes all at once, a sorted set (TreeMap, std::set, SortedList) is often simpler.
What it costs
| Operation | Time | Space |
|---|---|---|
| Peek at the min (or max) | O(1) | O(1) |
| Push or pop | O(log n) | O(1) |
| Build a heap from n items (heapify) | O(n) | O(n) |
| Top k of n items with a size-k heap | O(n log k) | O(k) |
| Merge k sorted lists, N items in total | O(N log k) | O(k) |
| Remove an arbitrary item | O(n), or lazy deletion | O(1) |
Built into your language
PriorityQueue<Integer> minH = new PriorityQueue<>(); // min heap
PriorityQueue<Integer> maxH = new PriorityQueue<>(Collections.reverseOrder()); // max heap
minH.offer(5); minH.offer(1);
minH.peek(); // 1 (null when empty)
minH.poll(); // 1, removed
minH.size();
// by the first field, then the second: use Integer.compare, never a - b
PriorityQueue<int[]> pq = new PriorityQueue<>(
(a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1])); import heapq
h = [5, 1, 8]
heapq.heapify(h) # O(n), h is now a min heap
heapq.heappush(h, 3)
h[0] # 1: peek
heapq.heappop(h) # 1, removed
heapq.heappushpop(h, 4) # push 4, then pop the smallest
heapq.nlargest(2, [5, 1, 8]) # [8, 5]
heapq.heappush(h, -7) # max heap: push negatives, negate on the way out
heapq.heappush(h, (2, "b")) # tuples compare by the first item, then the next priority_queue<int> maxH; // max heap by default
priority_queue<int, vector<int>, greater<int>> minH; // min heap
minH.push(5); minH.push(1);
minH.top(); // 1
minH.pop(); // removes it (returns nothing)
// pairs compare by first, then second
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
pq.push({2, 7}); // JavaScript has no built-in heap: keep a small class (it is in every template below)
const h = new MinHeap(); // min heap of numbers
h.push(5); h.push(1);
h.peek(); // 1
h.pop(); // 1, removed
h.size; // 1
const maxH = new MinHeap((a, b) => a > b); // max heap: flip the comparison
const byFirst = new MinHeap((a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1])); Mistakes everyone makes
- Writing the Java comparator as
(a, b) -> a - b: it overflows for large or negative values. UseInteger.compare(a, b). - Forgetting that Python's
heapqand C++'sgreater<int>give a min heap, while C++'s plainpriority_queueis a max heap. - Iterating over or printing a heap and expecting sorted order: only the top is guaranteed. Pop to get items in order.
- Pushing all n items into a max heap and popping k times, when a size-k min heap does it in O(k) memory.
- Trying to update an item inside the heap. Push the new version and skip the stale one when it reaches the top.
The 4 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Top k, kth largest and repeatedly taking the best Keep a min heap of size k: the top is the kth largest, and anything smaller than it can never make the cut. When you instead keep taking the biggest item and putting something back, use a max heap. 4 variations · 12 problems
- 2 Custom comparators: ordering by several keys The heap is only as good as its comparator. Compare the main key first and break ties with the next one, so "most frequent, then smallest value" or "highest priority, then highest id" comes out on top. 2 variations · 5 problems
- 3 Merge k sorted lists and arrays Put the first item of every sorted source in a min heap. Pop the smallest, output it, and push the next item from the same source. N items from k sources cost O(N log k). 3 variations · 4 problems
- 4 Advanced heaps: two heaps, lazy deletion and best-first search Heaps combined with other ideas: two heaps that split the data in half for a running median, a frontier that always expands the best candidate next, greedy choices from options you have already passed, and lazy deletion for items that expire. 5 variations · 12 problems