Skip to main content
Hard Heap / Priority Queue High frequency

Find Median from Data Stream

Open on LeetCode

Approach Summary

Maintain a max-heap for the lower half and min-heap for the upper half. Balance their sizes; median is the top of the larger or average of both tops.

Full Solution & Approach

A running median is the boundary between the lower and upper halves of the data, so maintain both halves explicitly with two heaps: a max-heap for the lower half and a min-heap for the upper half. Add each number to the lower max-heap, then rebalance: move the largest of the lower half into the upper half whenever the lower half has more than one extra element, and swap the tops if ordering is violated. The invariant is that both halves differ in size by at most one and every value in the lower half is at most every value in the upper half. The median is then the top of the larger heap, or the average of the two tops when sizes are equal. Each add does O(log n) heap work; the median is read in O(1). The two-heaps pattern is the standard answer for streaming percentile questions.

Each add performs at most a constant number of O(log n) heap operations — O(log n) per add. Both heaps together store n elements — O(n) space.

Solution Code

Solution

import heapq

class MedianFinder:
    def __init__(self):
        self.low = []   # max-heap (negated)
        self.high = []  # min-heap

    def add_num(self, num: int) -> None:
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def find_median(self) -> float:
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

Edge Cases to Watch

  • Empty stream — the problem guarantees findMedian is never called on an empty structure
  • Odd count — the larger heap holds the median at its top
  • Even count — average of the two tops
  • Duplicate values — heaps store every copy

How to Recognize This Pattern

  • Running median
  • Two heaps pattern

Complexity Analysis

Time Complexity

O(log n) add, O(1) median

Space Complexity

O(n)

Tags

Two Heaps Design Sorting

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee