Find Median from Data Stream
The problem
Section titled “The problem”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.5add 3 -> findMedian() = 2Key insight
Section titled “Key insight”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]) / 2export class MedianFinder { // Heap: a standard binary heap (LeetCode provides MinPriorityQueue / MaxPriorityQueue) private low = new Heap<number>((a, b) => b - a); // max-heap: the smaller half private high = new Heap<number>((a, b) => a - b); // min-heap: the larger half
addNum(num: number): void { // Route through low so the largest of the small half moves to high this.low.push(num); this.high.push(this.low.pop()!); if (this.high.size > this.low.size) this.low.push(this.high.pop()!); // low: same size or one bigger }
findMedian(): number { if (this.low.size > this.high.size) return this.low.peek()!; return (this.low.peek()! + this.high.peek()!) / 2; }}import java.util.Collections;import java.util.PriorityQueue;
class MedianFinder { private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder()); // max-heap: smaller half private final PriorityQueue<Integer> high = new PriorityQueue<>(); // min-heap: larger half
public void addNum(int num) { // Route through low so the largest of the small half moves to high low.offer(num); high.offer(low.poll()); if (high.size() > low.size()) low.offer(high.poll()); // low: same size or one bigger }
public double findMedian() { if (low.size() > high.size()) return low.peek(); return ((long) low.peek() + high.peek()) / 2.0; // long: avoid int overflow }}Complexity
Section titled “Complexity”- Time: O(log n) per
addNum, O(1) perfindMedian— 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.
Watch out for
Section titled “Watch out for”- Push through the other heap. Pushing to
low, moving its root tohigh, then rebalancing guarantees every low value is at most every high value, with noifon 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
longbefore 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
MinPriorityQueueandMaxPriorityQueue) and offer to implement it.
Variations
Section titled “Variations”Sliding Window Median (LeetCode 480)
Section titled “Sliding Window Median (LeetCode 480)”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.
IPO (LeetCode 502)
Section titled “IPO (LeetCode 502)”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 (LeetCode 4)
Section titled “Median of Two Sorted Arrays (LeetCode 4)”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.