CodeArchon

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
0
curr
2
1
3
2
4
3
5
4
MapDams | 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.

1import heapq
2class MedianFinder:
3 def __init__(self):
4 self.lo, self.hi = [], []
5 def addNum(self, x):
6 heapq.heappush(self.lo, -x)
7 heapq.heappush(self.hi, -heapq.heappop(self.lo))
8 if len(self.hi) > len(self.lo):
9 heapq.heappush(self.lo, -heapq.heappop(self.hi))
10 def findMedian(self):
11 if len(self.lo) > len(self.hi): return -self.lo[0]
12 return (-self.lo[0] + self.hi[0]) / 2
Variables
added=1
leftSize=1
rightSize=0
median=1

How to think about it

  1. Lower-half max-heap: top = largest of lower half.
  2. Upper-half min-heap: top = smallest of upper half.
  3. 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 1medians: 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