SDE & MLE Prep

295. Find Median from Data Stream

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