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.

4 patterns · 33 problems · Java, Python, C++ and JavaScript

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, pass Collections.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

OperationTimeSpace
Peek at the min (or max)O(1)O(1)
Push or popO(log n)O(1)
Build a heap from n items (heapify)O(n)O(n)
Top k of n items with a size-k heapO(n log k)O(k)
Merge k sorted lists, N items in totalO(N log k)O(k)
Remove an arbitrary itemO(n), or lazy deletionO(1)

Built into your language

Library calls
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]));

Mistakes everyone makes

  • Writing the Java comparator as (a, b) -> a - b: it overflows for large or negative values. Use Integer.compare(a, b).
  • Forgetting that Python's heapq and C++'s greater<int> give a min heap, while C++'s plain priority_queue is 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. 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. 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. 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. 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