Skip to content

Find Median from Data Stream

HardLeetCode #295Time O(log n) per add, O(1) per medianSpace O(n)

Design a class MedianFinder with two methods: addNum(num) stores a number, and findMedian() returns the median of everything added so far. With an even count, the median is the mean of the two middle values.

add 1, add 2 -> findMedian() = 1.5
add 3 -> findMedian() = 2

Keeping a sorted array makes findMedian O(1) but each insert O(n). Sorting on every query is O(n log n). Both redo work.

You only ever need the middle one or two values. Split the numbers into a smaller half and a larger half. Keep the smaller half in a max-heap (its root is the biggest small number) and the larger half in a min-heap (its root is the smallest large number). Keep the sizes equal, or with the low half one bigger. The median is then the low root, or the mean of both roots. Each insert rebalances in O(log n).

Show solutionHide solution
import heapq
class MedianFinder:
def __init__(self):
self.low = [] # max-heap (negated values): the smaller half
self.high = [] # min-heap: the larger half
def add_num(self, num: int) -> None:
# Route through low so the largest of the small half moves to high
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low): # keep low the same size or one bigger
heapq.heappush(self.low, -heapq.heappop(self.high))
def find_median(self) -> float:
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2
  • Time: O(log n) per addNum, O(1) per findMedian — a few heap pushes and pops on insert; the median only reads the roots.
  • Space: O(n) — every number is stored in one of the two heaps.
  • Push through the other heap. Pushing to low, moving its root to high, then rebalancing guarantees every low value is at most every high value, with no if on the new number’s size.
  • Odd versus even. Pick one convention (low half is the bigger one when odd) and read the median from that side.
  • Return a float, and watch overflow. In Java, add as long before halving. Python’s max-heap needs negated values: negate on the way in and out.
  • JS/TS interviews. There is no built-in heap. Say you will assume a heap helper exists (LeetCode gives you MinPriorityQueue and MaxPriorityQueue) and offer to implement it.

Median of every window of size k. The trick: the same two-heap split, but you must also remove the element leaving the window. Use lazy deletion (mark it, discard it when it reaches a root) or a sorted structure with removal.

Pick at most k projects to maximize capital, where each needs a minimum capital to start. The trick: sort projects by cost, push every affordable project’s profit onto a max-heap, and take the best. Repeat k times.

Median of two sorted arrays in O(log(m + n)). The trick: not a heap. Binary search for the partition point that splits both arrays into a left half and a right half where every left value is at most every right value.