Find Median from Data Stream

Hard

Topics
HeapDesignTwo PointersSorting

The median is the middle value in an ordered list; for an even-sized list it is the average of the two middle values. Design a structure that supports a stream of integers. Implement MedianFinder with addNum(num) to add an integer, and findMedian() to return the median of all elements so far. Medians are reported to one decimal place (e.g. 2.0, 1.5).

Example 1

returnsMedianFinder()addNum(1)addNum(2)findMedian()1.5addNum(3)findMedian()2
Numbers arrive one at a time and the median can be asked for at any point, over everything seen so far. With an even count it is the average of the middle two, so the answer is not always one of the numbers that were added.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"], values = [[],[1],[2],[],[3],[]]
Output: [null,null,null,1.5,null,2.0]

Constraints

  • -10^5 <= num <= 10^5
  • At most 5*10^4 calls to addNum and findMedian.
  • findMedian is only called on a non-empty structure.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Keep the lower half of the numbers in a max-heap and the upper half in a min-heap, balanced in size. The median is then either the top of one heap (odd count) or the average of both tops (even count) — all in O(log n) per insert.

Approach

  1. Push the new value into the max-heap (lower half), then move its top into the min-heap so ordering holds.
  2. If the min-heap grows larger, move its top back so the max-heap has equal or one more element.
  3. findMedian returns the max-heap top when the total is odd, else the average of the two tops.

Dry Run

lo is a MAX-heap of the lower half, stored negated. hi is a min-heap of the upper half.

addNum 1    push -1              lo=[-1]      hi=[]
            move top to hi       lo=[]        hi=[1]
            hi is bigger, move back           lo=[-1]      hi=[]
addNum 2    push -2              lo=[-2, -1]  hi=[]
            move top to hi       lo=[-1]      hi=[2]
            sizes equal, no rebalance
findMedian  equal sizes, so average the two tops: (1 + 2) / 2    -> 1.5
addNum 3    push -3              lo=[-3, -1]  hi=[2]
            move top to hi       lo=[-1]      hi=[2, 3]
            hi is bigger, move back           lo=[-2, -1]  hi=[3]
findMedian  lo is bigger, so its top IS the median               -> 2.0

Why every add pushes to lo and then immediately moves to hi: that round trip is
what guarantees the number lands in the correct half. Pushing straight to
whichever heap looks right by comparing against a top is where this gets subtly
wrong on the first element.

Complexity

  • Time — O(log n) per addNum: each insert does a constant number of heap pushes/pops; findMedian is O(1).
  • Space — O(n): the two heaps together store every number.

Common Pitfalls

  • Rebalance after every insert so the two heaps never differ in size by more than one.
  • For even counts, average as a float so 1 and 2 give 1.5, not 1.

Full Solution — all languages

import heapq

class MedianFinder:
    def __init__(self):
        self.lo = []  # max-heap via negation (lower half)
        self.hi = []  # min-heap (upper half)
    def addNum(self, num):
        heapq.heappush(self.lo, -num)
        heapq.heappush(self.hi, -heapq.heappop(self.lo))
        if len(self.hi) > len(self.lo):
            heapq.heappush(self.lo, -heapq.heappop(self.hi))
    def findMedian(self):
        if len(self.lo) > len(self.hi):
            return float(-self.lo[0])
        return (-self.lo[0] + self.hi[0]) / 2.0
SensAI
Beta
Tap the mic to stop voice mode