Skip to content
Bill Liao
Go back

Find Median from Data Stream

Edit page

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

Implement the MedianFinder class:

Example 1:

Input [“MedianFinder”, “addNum”, “addNum”, “findMedian”, “addNum”, “findMedian”] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0]

Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0

Constraints:

Follow up:

Approach: Two Heaps (Max-Heap + Min-Heap)

Algorithm

  1. Keep two heaps: a max-heap for the smaller half of the numbers and a min-heap for the larger half
  2. addNum: push into the max-heap, then move the largest element to the min-heap; rebalance so the two heaps differ in size by at most one
  3. findMedian: if the sizes are equal, average the two roots; otherwise return the root of the larger heap

Time & Space Complexity

Java Implementation

import java.util.Collections;
import java.util.PriorityQueue;

public class MedianFinder {

    private final PriorityQueue<Integer> maxHeap;
    private final PriorityQueue<Integer> minHeap;

    public MedianFinder() {
        maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        minHeap = new PriorityQueue<>();
    }

    public void addNum(int num) {
        maxHeap.offer(num);
        minHeap.offer(maxHeap.poll());

        if (maxHeap.size() < minHeap.size()) {
            maxHeap.offer(minHeap.poll());
        }
    }

    public double findMedian() {
        if (maxHeap.size() > minHeap.size()) {
            return maxHeap.peek();
        }
        return (maxHeap.peek() + minHeap.peek()) / 2.0;
    }

    // Test method
    public static void main(String[] args) {
        MedianFinder medianFinder = new MedianFinder();
        medianFinder.addNum(1);
        medianFinder.addNum(2);
        System.out.println(medianFinder.findMedian()); // return 1.5
        medianFinder.addNum(3);
        System.out.println(medianFinder.findMedian()); // return 2.0
    }
}

Example Walkthrough

Inserting 1, 2, 3:

  1. addNum(1): maxHeap={1}, sizes equal
  2. addNum(2): push 2 to maxHeap -> maxHeap={2,1}; move max to minHeap -> maxHeap={1}, minHeap={2}. Even sizes, median=(1+2)/2=1.5
  3. addNum(3): push to maxHeap -> maxHeap={3,1}; move max to minHeap -> maxHeap={1}, minHeap={2,3}; rebalance since maxHeap < minHeap -> maxHeap={2,1}, minHeap={3}. maxHeap larger, median=2.0

Key Points

  1. Invariant: maxHeap holds the smaller half, minHeap holds the larger half, and sizes differ by at most one
  2. Top of Heaps: The median candidates are always the roots of the two heaps
  3. Balancing Step: The maxHeap is never smaller than minHeap, keeping the median in maxHeap for odd sizes
  4. Follow-Up: For bounded ranges [0,100], a frequency array with prefix sums gives O(100) operations
  5. Precision: Averaging in double arithmetic keeps results within the 10-5 tolerance

Edit page
Share this post:

Previous Post
Sequence Reconstruction
Next Post
Merge k Sorted Lists