Lesson 140 of 296
Heaps: top-k, merging and medians
What you will learn
- The "size-k heap" trick
- Kth Largest Element in an Array
- K Closest Points to Origin
- Merge K Sorted Lists
- Find Median from Data Stream
On this page
The size-k heap trick
To find the k largest items, keep a min-heap of size k. For each item, push it; if the heap grows beyond k, pop the smallest. At the end, the heap holds the k largest, and its top is the kth largest.
Why a min-heap for the largest items? The top of the heap is the weakest of your current top k, the one to throw out when something better arrives.
Cost: O(n log k) time, O(k) space. Better than sorting (O(n log n)) when k is small, and it works on a stream where you cannot hold all the data.
Kth Largest Element in an Array
Problem (LeetCode 215): [3, 2, 1, 5, 6, 4], k = 2 → 5.
function findKthLargest(nums: number[], k: number): number {
const heap = new Heap<number>((a, b) => a - b);
for (const n of nums) {
heap.push(n);
if (heap.size > k) heap.pop();
}
return heap.peek()!;
}Other approaches to mention: sorting, O(n log n); quickselect (a quicksort-style partition that only recurses into one side), O(n) on average but O(n²) in the worst case.
K Closest Points to Origin
Problem (LeetCode 973): the k points closest to (0, 0).
Keep a max-heap of size k by distance; the top is the farthest of the current best, so it is the one to remove. Compare squared distances (x² + y²): no need for square roots, because the order is the same.
function kClosest(points: [number, number][], k: number): [number, number][] {
const distance = ([x, y]: [number, number]) => x * x + y * y;
const heap = new Heap<[number, number]>((a, b) => distance(b) - distance(a));
for (const point of points) {
heap.push(point);
if (heap.size > k) heap.pop();
}
const result: [number, number][] = [];
while (heap.size > 0) result.push(heap.pop()!);
return result;
}O(n log k).
Merge K Sorted Lists
Problem (LeetCode 23, hard): merge k sorted linked lists into one.
Idea: the next smallest node is always one of the k current heads. Put the heads in a min-heap; pop the smallest, add it to the result, and push its next.
function mergeKLists(lists: (ListNode | null)[]): ListNode | null {
const heap = new Heap<ListNode>((a, b) => a.val - b.val);
for (const head of lists) {
if (head !== null) heap.push(head);
}
const dummy = new ListNode(0);
let tail = dummy;
while (heap.size > 0) {
const node = heap.pop()!;
tail.next = node;
tail = node;
if (node.next !== null) heap.push(node.next);
}
tail.next = null;
return dummy.next;
}With N total nodes: O(N log k) time, O(k) heap space. (Alternative: merge the lists in pairs, like merge sort, also O(N log k).)
Find Median from Data Stream
Problem (LeetCode 295, hard): numbers arrive one at a time; at any moment, return the median.
Idea: two heaps.
- A max-heap
lowholds the smaller half of the numbers. - A min-heap
highholds the larger half. - Keep them balanced:
lowhas the same number of items ashigh, or one more. - The median is the top of
low(odd count) or the average of both tops (even count).
class MedianFinder {
private low = new Heap<number>((a, b) => b - a);
private high = new Heap<number>((a, b) => a - b);
addNum(num: number): void {
this.low.push(num);
this.high.push(this.low.pop()!);
if (this.high.size > this.low.size) {
this.low.push(this.high.pop()!);
}
}
findMedian(): number {
if (this.low.size > this.high.size) return this.low.peek()!;
return (this.low.peek()! + this.high.peek()!) / 2;
}
}Adding to low, then moving its largest to high, guarantees every number in low is at most every number in high. Then rebalance sizes.
O(log n) per insert, O(1) per median.
How to say it in an interview
"For top-k problems I keep a heap of size k: a min-heap for the k largest so the top is the kth largest and the first to evict, giving O(n log k) and working on streams. For K Closest Points I use a max-heap on squared distance. For Merge K Sorted Lists I keep the current head of each list in a min-heap, for O(N log k). For a running median I keep a max-heap of the lower half and a min-heap of the upper half, balanced so the median comes from the tops."
Key words
| Word | Meaning |
|---|---|
| Top-k | The k largest or smallest items |
| Quickselect | Partition-based selection, average O(n) |
| Median | The middle value of sorted data |
| Stream | Data that arrives over time |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.