Topic · 3 patterns
Heaps & Priority Queues patterns
A heap hands you the best element so far in O(log n). Top-K keeps a heap of size k instead of sorting everything, two heaps hold the lower and upper halves of a stream so the median is always on top, and k-way merge pulls the next smallest item from k sorted lists.
The patterns
Top-K Elements
O(n log k)
Keep a heap of size k (min-heap for k-largest), pushing and popping so only the k best ever survive.
Spot it: "k largest / smallest / most frequent / closest", "the k-th ...", top-k of a stream, or repeatedly pick the min/max as items change.
Two Heaps
O(log n) per op
A max-heap holds the lower half, a min-heap the upper half; keep their sizes balanced and the median sits on top.
Spot it: Running median, sliding-window median, or two pools picked by different keys (IPO: affordable vs most profitable).
Learn first: Top-K Elements
K-way Merge
O(N log k)
Push the head of each list into a min-heap; repeatedly pop the smallest and push that list's next element.
Spot it: k already-sorted lists/arrays/rows to combine, k-th smallest across them, smallest range covering all lists, or merging sorted generators.
Learn first: Top-K Elements
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| "k largest / smallest / most-frequent / closest", or "the kth …" | Top-K Heap |
| Median of a running stream; need max-of-low-half and min-of-high-half together | Two Heaps |
| k already-sorted lists/arrays to merge, or smallest range covering all k | K-way Merge |
Easy to confuse
Median of Two Sorted Arrays looks like K-way Merge, but it’s Binary Search
Merging is O(m + n); binary searching the partition is O(log min(m, n)).
Kth Smallest Element in a Sorted Matrix looks like K-way Merge, but it’s Binary Search on the Answer
Heap works, but binary search on the value with a staircase count is often better.
Task Scheduler looks like Top-K Elements, but it’s Greedy
A heap simulation works, but a counting formula on the max frequency gives O(n).
Last Stone Weight II looks like Top-K Elements, but it’s 0/1 Knapsack
Its sibling last-stone-weight is a heap simulation, but greedy smashing is not optimal here. Every outcome is |S1 - S2| for some split, so find the subset sum closest to total/2.
Find the K-Sum of an Array looks like Subsets / Permutations / Combinations, but it’s K-way Merge
Enumerating subsets is 2n. Sort |a| and pop k times from a frontier heap with the 'extend / replace last' successor rule.
Used together
When: repeatedly pick the most frequent/cheapest/available item; time-based simulation. The greedy choice changes as the state evolves, so a static sort is not enough.
Merge Intervals + Top-K Elements
When: minimum rooms/machines; assign rooms to customers. Counting concurrency (or assigning resources) needs to know the earliest-free resource.
Sweep Line (events + active set) + Top-K Elements
When: skyline / max active value over time. Need the max active value at each event, which counts cannot give.
Topological Sort + Top-K Elements
When: lexicographically smallest topological order; 'course 1 as early as possible'. When several vertices are free, the order among them must optimise something (lexicographic).
Top-K Elements
- Kth Largest Element in a StreamEasy
- Last Stone WeightEasy
Two Heaps
- Find Median from Data StreamHard
K-way Merge
- Merge Two Sorted ListsEasy
- Merge Sorted ArrayEasy
Further reading
- Heap visualizerVisuAlgo
See sift-up/sift-down and heapify in O(n).
- Heap cheatsheetTech Interview Handbook
Top-K, two heaps and K-way merge recipes.
- std::priority_queuecppreference
Comparator semantics (max-heap default) that trip up C++ users.
- Find Median from Data Stream editorialLeetCode
Canonical two-heaps problem with full analysis.
- Heaps and Heap SortAbdul Bari
Whiteboard walk-through of heap operations and heap sort.