Find Median from Data Stream
Build a data structure to find the median of a stream of numbers Median = middle value when sorted (or average of two middle values) Example: add_num(1), add_num(2), find_median() -> 1.5 add_num(3), find_median() -> 2.0
Two heaps: a max-heap for the lower half and a min-heap for the upper half, kept balanced (differ by at most 1). Median comes from comparing heap tops - O(log n) insertion, O(1) median lookup. The quintessential 'two heaps' pattern problem.
Examples
You write
MedianFinder: add_num(num: int), find_median()
Example 1
- Input
- MedianFinder(), addNum(1), addNum(2), findMedian()
- returns
- 1.5
Example 2
- Input
- MedianFinder(), addNum(1), addNum(2), findMedian(), addNum(3), findMedian()
- returns
- 2.0
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsHeaps
I reach for it when
- You need the k largest or k smallest items.
- You repeatedly take the best remaining item.
Say this before you type. Say what the heap holds, how big it stays, and what sits on top.
All 22 Heaps problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.