Pattern #13
Heap & Top K
EssentialRepeated extract-min/max or maintain the K best under a stream.
When to use
You need the smallest, largest, or K most frequent elements without fully sorting every time.
Recognition cues
- Kth largest / top K frequent
- Merge K sorted lists
- Median from stream (two heaps)
Common pitfalls
- Min-heap vs max-heap confusion for top-K
- Storing only values when you need (freq, key) pairs
- O(n log n) sort when O(n log k) heap is enough
90-second recognition drill
Which pattern fits best?
- Kth largest / top K frequent
- Merge K sorted lists
- Median from stream (two heaps)
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
1
1
1
2
2
3
map1→32→23→1
K = 2
Top K frequent. Count frequencies first.
How to think about it
A heap keeps the boundary of interest. For top K largest, a min-heap of size K stores the current winners; the root is the weakest winner. For streams, two heaps can balance lower/upper halves for the median.
Template shapes
| Shape | Core move | Notes |
|---|---|---|
| Top K | Min-heap size K | Evict root if new is better |
| K-way merge | Min-heap of heads | Push next from same list |
| Median | Max-heap + min-heap | Rebalance sizes |
Complexity baseline
O(n log k) typical for top-K; O(log n) per insert/pop. Space O(k) or O(n).
From template to problem
- Clarify: K largest, K smallest, or K frequent?
- Pick heap orientation so the root is the one you are ready to discard.
- Process elements; maintain heap size ≤ K when applicable.
- Extract or convert heap to the answer format.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Heap & Top K · Template
/** Heap / top-K template: kth largest via min-heap of size k. */
export function findKthLargest(nums: number[], k: number): number {
const heap: number[] = [];
for (const x of nums) {
heap.push(x);
heap.sort((a, b) => a - b);
if (heap.length > k) heap.shift();
}
return heap[0]!;
}
/** Heap / top-K template: kth largest via min-heap of size k. */
export function findKthLargest(nums: number[], k: number): number {
const heap: number[] = [];
for (const x of nums) {
heap.push(x);
heap.sort((a, b) => a - b);
if (heap.length > k) heap.shift();
}
return heap[0]!;
}
#StatusProblemTypeDifficultyDone
- 1#23 Merge k Sorted ListsGuidehard
- 2#215 Kth Largest Element in an ArrayGuidemedium
- 3#295 Find Median from Data StreamGuidehard
- 4#347 Top K Frequent ElementsGuidemedium
- 5#373 Find K Pairs with Smallest SumsGuidemedium
- 6#973 K Closest Points to OriginGuidemedium