295. Find Median from Data Stream
Asked at 41Amazon63Apple61Microsoft53Google51Meta50Bloomberg39IXL95Adobe69Spotify69Intuit67TikTok58DE Shaw38Cohesity100Splunk100Tinder100Citadel89Okta89StackAdapt83WorldQuant83SIG81KLA69Twitch69Coupang68PayPal67Anduril66Walmart Labs66Sprinklr65Tekion63Arcesium61Oracle60Flipkart59eBay53Samsung53Uber50Pinterest49Visa48Rippling46Goldman Sachs40Snowflake39Yandex28Salesforce28
Problem
Design MedianFinder with addNum(num), which adds a number from a data stream, and findMedian(), which returns the median of all numbers so far (the mean of the two middle ones when the count is even).
Example: add 1, add 2 → findMedian() = 1.5; add 3 → findMedian() = 2.0
Constraints: up to 5·10⁴ calls. Follow-up: what if all numbers are in [0, 100]?
lo = max-heap of the smaller half, hi = min-heap of the larger half, len(lo) ∈ {len(hi), len(hi)+1}. Push into lo, move its max to hi, rebalance. Median = top of lo, or the average of both tops.
stream 5 2 8 1
lo (max-heap) [2, 1] | hi (min-heap) [5, 8]
median = (2 + 5) / 2 = 3.5
Complexity: O(log n) add, O(1) median.
class MedianFinder:
def __init__(self):
self.lo, self.hi = [], [] # lo stores negatives (max-heap)
def addNum(self, num: int) -> None:
heappush(self.lo, -num)
heappush(self.hi, -heappop(self.lo))
if len(self.hi) > len(self.lo):
heappush(self.lo, -heappop(self.hi))
def findMedian(self) -> float:
if len(self.lo) > len(self.hi):
return float(-self.lo[0])
return (-self.lo[0] + self.hi[0]) / 2
mf = MedianFinder()
mf.addNum(1); mf.addNum(2)
assert mf.findMedian() == 1.5
mf.addNum(3)
assert mf.findMedian() == 2.0
class MedianFinder {
private final PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder());
private final PriorityQueue<Integer> hi = new PriorityQueue<>();
public void addNum(int num) {
lo.add(num);
hi.add(lo.poll());
if (hi.size() > lo.size()) lo.add(hi.poll());
}
public double findMedian() {
return lo.size() > hi.size() ? lo.peek() : (lo.peek() + (double) hi.peek()) / 2;
}
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
type MedianFinder struct {
lo IntHeap // smaller half, stored negated (a max-heap)
hi IntHeap // larger half
}
func Constructor() MedianFinder {
return MedianFinder{}
}
func (this *MedianFinder) AddNum(num int) {
heap.Push(&this.lo, -num)
heap.Push(&this.hi, -heap.Pop(&this.lo).(int)) // the largest of the small half moves up
if this.hi.Len() > this.lo.Len() {
heap.Push(&this.lo, -heap.Pop(&this.hi).(int))
}
}
func (this *MedianFinder) FindMedian() float64 {
if this.lo.Len() > this.hi.Len() {
return float64(-this.lo[0])
}
return float64(-this.lo[0]+this.hi[0]) / 2
}