Tech Interview RoomStudy guides

Heaps & Intervals

Find the median of a data stream. Compare sorting on demand, a sorted list with binary insertion, and two heaps.

Advanced · 2 min read · Lesson 5 of 5 in Heaps & Intervals

Problem

Support addNum(x) and findMedian() over a growing stream. After 1, 2 → 1.5; after 3 → 2.

Pattern

Two heaps: a max-heap holds the smaller half and a min-heap the larger half; balanced sizes put the median at the heap tops.

Approach 1: Store all numbers and sort on each query (feasible, O(n log n) per query)

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class MedianSortEachTime {
    private final List<Integer> nums = new ArrayList<>();
    void add(int x) { nums.add(x); }
    double median() {
        List<Integer> s = new ArrayList<>(nums);
        Collections.sort(s);
        int n = s.size();
        return n % 2 == 1 ? s.get(n / 2) : (s.get(n / 2 - 1) + s.get(n / 2)) / 2.0;
    }
}

Approach 2: Keep a sorted list with binary-search insertion (O(n) add, O(1) median)

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class MedianSortedList {
    private final List<Integer> s = new ArrayList<>();
    void add(int x) {
        int i = Collections.binarySearch(s, x);
        s.add(i < 0 ? -(i + 1) : i, x);                          // O(log n) search + O(n) shift
    }
    double median() {
        int n = s.size();
        return n % 2 == 1 ? s.get(n / 2) : (s.get(n / 2 - 1) + s.get(n / 2)) / 2.0;
    }
}

Approach 3: Two heaps (O(log n) add, O(1) median) — optimal

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

class MedianTwoHeaps {
    private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());   // max-heap
    private final PriorityQueue<Integer> high = new PriorityQueue<>();                             // min-heap

    void add(int x) {
        low.offer(x);
        high.offer(low.poll());                                  // largest of the low half moves up
        if (high.size() > low.size()) low.offer(high.poll());    // keep low.size() >= high.size()
    }
    double median() {
        return low.size() > high.size() ? low.peek() : (low.peek() + (long) high.peek()) / 2.0;
    }
}

class MedianDemo {
    public static void main(String[] args) {
        MedianSortEachTime a = new MedianSortEachTime(); MedianSortedList b = new MedianSortedList(); MedianTwoHeaps c = new MedianTwoHeaps();
        for (int x : new int[] {5, 15, 1, 3, 8}) {
            a.add(x); b.add(x); c.add(x);
            System.out.println(a.median() + " " + b.median() + " " + c.median());
        }   // 5.0, 10.0, 5.0, 4.0, 5.0 (each x3)
    }
}

Feasible → optimal

Sorting per query O(n log n) → sorted list O(n) per insert → two heaps O(log n) insert and O(1) median.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): sliding window median.

Two heaps plus lazy deletion of elements leaving the window (a map of "to be removed" counts, cleaned when they reach a heap top), or two TreeMap multisets that support direct removal. O(n log k).

Related (same pattern): K closest points to the origin.

Max-heap of size k keyed by squared distance (pop when size exceeds k): O(n log k). Quickselect on distances gives O(n) average. Sorting all points is the O(n log n) feasible answer.