Heaps
People arrive one at a time and join one of two teams: the shorter half and the taller half. The shorter team only watches its tallest member, and the taller team only its shortest. The median is always where the two teams meet, so nobody ever lines everyone up by height.
2 · Watch
Heaps in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Find Median from Data Stream
or try
1–8 numbers from -99 to 99, in the order they arrive.Two empty heaps: the lower half on the left, the upper half on the right.Step 1 of 16. Two empty heaps. 4 numbers arriving. No median yet.
Step 1 of 16
solution.ts
class MedianFinder {
low = new MaxHeap(); // smaller half
high = new MinHeap(); // larger half
addNum(num: number) {
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;
}
}
▶ marks the line running now
4 · Your turn
0 of 1 problems solved
Start from this
// Min-heap: the smallest kept item is on top.
const heap = new MinHeap<number>();
for (const x of nums) {
heap.push(x);
// Too many: drop the smallest, keep the k largest.
if (heap.size() > k) heap.pop();
}
// The top is now the kth largest.
return heap.peek();Easy ways to go wrong
- Using a max-heap for “k largest”. A min-heap of size k is cheaper.
- Forgetting that Python’s heapq is a min-heap. Negate values for a max-heap.
- Sorting everything when you only need the top k.
- Hard01
Find Median from Data Stream
The one you just watched. Write it from memory.
Keep the small half and big half apart, with each top on hand.
- Time
- O(log n) per add
- Space
- O(n)