Heaps and Priority Queues
Use min-heaps and max-heaps for top-k, k-way merge, scheduling and running median problems.
Intermediate · about 6 hours · difficulty 3/5
Learn first: Binary Tree Traversals, Sorting Algorithms and Custom Sorts
A heap gives you the smallest (or largest) element in O(1) and insert or remove in O(log n). Whenever a problem keeps asking for "the current best", think heap.
How it works
A binary heap is a complete tree stored in an array: children of i are 2i + 1 and 2i + 2. Push sifts up, pop sifts down. Building a heap from n elements takes O(n), not O(n log n).
Key patterns
- Top K: keep a min-heap of size k for the k largest (Kth Largest Element, Top K Frequent Elements, K Closest Points to Origin). Cost O(n log k).
- K-way merge: push the head of each list (Merge k Sorted Lists, Kth Smallest Element in a Sorted Matrix, Find K Pairs with Smallest Sums).
- Two heaps: a max-heap for the lower half and a min-heap for the upper half (Find Median from Data Stream).
- Greedy with a heap: Task Scheduler, Reorganize String, Minimum Cost to Connect Sticks, IPO, Meeting Rooms II (min-heap of end times).
- Heaps also power Dijkstra and Prim's algorithm in the graph section.
Pitfalls
- Using a max-heap of size n for top-k when a min-heap of size k is cheaper.
- Comparator direction confusion: C++ priority_queue is a max-heap by default; Java PriorityQueue and Python heapq are min-heaps.
- Updating an element's priority in place; push a new entry and skip stale ones instead.
You are ready to move on when you can implement a heap with sift-up and sift-down and solve Find Median from Data Stream.
Key concepts
- Array representation of a heap
- Sift up, sift down, heapify
- Top K with a size-k heap
- K-way merge
- Two heaps for running median
- Heap-based greedy scheduling
- Lazy deletion
Mini project
Implement a min-heap class from scratch, then solve these 9 in 7 days, log time and pattern: Kth Largest Element in an Array, Kth Largest Element in a Stream, Top K Frequent Elements, K Closest Points to Origin, Last Stone Weight, Merge k Sorted Lists, Task Scheduler, Meeting Rooms II, Find Median from Data Stream.
Check yourself
Why does finding the k largest elements use a min-heap of size k, and what is the time complexity?
Free resources
- VisuAlgo: binary heap (VisuAlgo)
- NeetCode roadmap: Heap (NeetCode)
- Python docs: heapq (Python)