hardHeap / Priority QueueAmazonGoogleFacebook
Dual Dam Median Watcher
Two reservoirs — a lower dam (max-heap) and an upper dam (min-heap) — split an incoming water-level stream so their peak levels always sandwich the running median.
Design a data structure that supports addNum(x) in O(log n) and findMedian() in O(1) for a stream of integers.
Choose approach
1
0curr
2
13
24
35
4MapDams | Left Max-Heap: [1] | Right Min-Heap: []
median→1
1/5
Narrationstep 1 of 5
Ingest 1. Left dam max = 1, right dam min = -. Median = 1.
Variables
added=1
leftSize=1
rightSize=0
median=1
How to think about it
- Lower-half max-heap: top = largest of lower half.
- Upper-half min-heap: top = smallest of upper half.
- Keep |lo| == |hi| or |lo| == |hi| + 1 for guaranteed O(1) median.
Edge cases to catch in interview
- Odd count -> median = lo.top().
- Even count -> median = (lo.top() + hi.top()) / 2.
Examples
Example 1
medians: 1, 1.5, 2{"stream":[1,2,3],"values":[1,2,3]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed