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.
K = 2
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 | Example |
|---|---|---|
| K-way merge | Min-heap of each list’s current head. Pop the smallest, append it, and push that node’s next. The heap stays at most k long |
LC 23 |
| Kth largest | Min-heap of size k. Push, and pop when the size passes k. The root is the kth largest. Quickselect to index n - k is the other pattern on this problem |
LC 215 |
| Running median | The low half is a max-heap and the high half a min-heap. Sizes differ by at most 1, and every low value is ≤ every high value. An odd count reads the low top. An even count averages the two tops |
LC 295 |
| Top-k frequent | The published write-up counts, then buckets by frequency, and reads from the high end until k values. A size-k heap is not the solution on that page. The highest count is at most n |
LC 347 |
| K smallest pairs | Seed (nums1[i], nums2[0]) for i < min(k, n). Pop the smallest sum and push the next index in that same nums2 row. The full matrix is never built |
LC 373 |
| K closest | Heap ordered by distance, farthest at the root. When the size passes k, pop the farthest. Order of the remaining points does not matter |
LC 973 |
Complexity baseline
O(n log k) typical for a size-k heap. LC 23 is O(N log k) over the total number of nodes. LC 295 is O(log n) per insertion. Space O(k) or O(n).
From template to problem
- Point the root at the value you are ready to discard: the smallest of the top-k largest (LC 215), or the farthest of the k closest (LC 973).
- A k-way merge pushes the next node from the list you just popped, not an arbitrary head (LC 23).
- Keep the two median heaps within one of each other, and keep the low top
≤the high top (LC 295). - LC 347 on this site is frequency buckets under hashing. Do not replace that write-up with a heap.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
private a: T[] = [];
private less: (x: T, y: T) => boolean;
constructor(less: (x: T, y: T) => boolean) {
this.less = less;
}
get size(): number {
return this.a.length;
}
peek(): T {
return this.a[0]!;
}
push(x: T): void {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.less(a[i]!, a[p]!)) break;
[a[i], a[p]] = [a[p]!, a[i]!];
i = p;
}
}
pop(): T {
const a = this.a;
const top = a[0]!;
const last = a.pop()!;
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1;
const r = l + 1;
let s = i;
if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
if (s === i) break;
[a[i], a[s]] = [a[s]!, a[i]!];
i = s;
}
}
return top;
}
}
/** Heap / top-K template: kth largest via a real binary min-heap of size k. */
export function findKthLargest(nums: number[], k: number): number {
const heap = new Heap<number>((a, b) => a < b);
for (const x of nums) {
if (heap.size < k) {
heap.push(x);
} else if (x > heap.peek()) {
heap.pop();
heap.push(x);
}
}
return heap.peek();
}
/** Heap / top-K template: kth largest via a real binary min-heap of size k. */
export function findKthLargest(nums: number[], k: number): number {
const heap = new Heap<number>((a, b) => a < b);
for (const x of nums) {
if (heap.size < k) {
heap.push(x);
} else if (x > heap.peek()) {
heap.pop();
heap.push(x);
}
}
return heap.peek();
}
- 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