Two Heaps

Keep a max-heap of the smaller half and a min-heap of the larger half to get running medians and balance two choices.

Advanced 2 min readLesson 17 of 25 Interview Q&A

Split the data into two halves: a max-heap holding the smaller half and a min-heap holding the larger half. The two heap tops sit right at the middle, so the median is always available in O(1), and each insert costs O(log n).

median = (5 + 7) / 2max-heap (small half)1 · 2 · 3 · top = 5min-heap (large half)top = 7 · 9 · 12
When to use this pattern
  • Median of a stream, or of a sliding window.
  • Problems that need the "largest of the small ones" and the "smallest of the large ones" at the same time.
  • Scheduling with two competing orders: e.g. IPO — projects you can afford (sorted by capital) vs. the most profitable one among them.

Find median from a data stream

Invariants: every element of lo is ≤ every element of hi, and lo has the same size as hi or one more.

class MedianFinder {
    PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()); // max-heap
    PriorityQueue<Integer> hi = new PriorityQueue<>();                           // min-heap

    void addNum(int x) {
        lo.offer(x);
        hi.offer(lo.poll());                  // move lo's largest to hi (keeps order)
        if (hi.size() > lo.size()) lo.offer(hi.poll());   // rebalance sizes
    }

    double findMedian() {
        return lo.size() > hi.size() ? lo.peek() : (lo.peek() + hi.peek()) / 2.0;
    }
}

Sliding window median

You also need to remove the element leaving the window. Heaps can't delete arbitrary items cheaply, so use lazy deletion: record the outgoing value in a "to delete" map and discard it when it surfaces at a heap top. Keep sizes balanced by counting only valid elements. Alternatives: two TreeMap/multisets (Java, C++), or SortedList in Python. Time O(n log k).

IPO (maximise capital)

Sort projects by required capital. Repeat k times: push every newly affordable project's profit onto a max-heap, then take the most profitable one. One "heap" here is the sorted array with a pointer, the other is the max-heap.

int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
    int n = profits.length;
    Integer[] idx = new Integer[n];
    for (int i = 0; i < n; i++) idx[i] = i;
    Arrays.sort(idx, (a, b) -> capital[a] - capital[b]);
    PriorityQueue<Integer> best = new PriorityQueue<>(Collections.reverseOrder());
    int i = 0;
    while (k-- > 0) {
        while (i < n && capital[idx[i]] <= w) best.offer(profits[idx[i++]]);
        if (best.isEmpty()) break;
        w += best.poll();
    }
    return w;
}
TimeO(log n) per insert, O(1) medianSpaceO(n)
Practice problems
  • Find Median from Data Streamhard
  • Sliding Window Medianlazy deletionhard
  • IPOsorted capital + max-heap of profithard
  • Find Right Intervaltwo heaps or sort + binary searchmedium
  • Kth Largest Element in a Streamone heap of size keasy
Key takeaways
  • Max-heap for the lower half, min-heap for the upper half; the tops are the median.
  • Keep sizes equal or lo one larger; push through lo to hi to keep order.
  • Sliding windows need lazy deletion or an ordered multiset.
  • The same "two priority orders" idea solves scheduling problems like IPO.
Interview questions
QWhy not just keep a sorted list and insert into it?medium

Insertion into a sorted array is O(n) because elements shift. Two heaps make each insert O(log n) and still give the median in O(1). A balanced BST or skip list also works and supports deletions, at a higher constant cost.

QHow would you handle the median when 99% of numbers fall in 0–100?hard

Keep a count array for 0–100 and find the median by walking cumulative counts (O(100)). Put rare outliers into small separate lists or heaps and adjust the median rank by their counts.