Video in progress

Numbers arrive as a stream. At any moment, how do you quickly return the median of everything received so far?

Two heaps: a max-heap for the smaller half and a min-heap for the larger half. I keep their sizes equal or differing by one. Adding is O(log n), and getting the median is O(1), from the tops of the heaps.

📖 Answer

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

    void add(int x) {
        low.add(x);
        high.add(low.poll());                 // the largest goes to the right side
        if (high.size() > low.size()) low.add(high.poll());  // balance: low >= high
    }

    double median() {
        return low.size() > high.size()
                ? low.peek()
                : ((long) low.peek() + high.peek()) / 2.0;
    }
}

The "pass it through twice" trick in add keeps the order automatically: every element in low is less than or equal to every element in high.

The (long) cast isn't for nothing: the sum of two large ints overflows.

Now the senior part. On prod this question usually comes in another form: "the p50 latency over the last 5 minutes".

  • In a sliding window median, you have to remove old elements from the heap. PriorityQueue.remove(Object) is O(n). The fix is lazy deletion (count the ones to be removed in a Map and drop them when they surface at the top) or two TreeMap<Integer, Integer> multisets.
  • At a million requests per second you can't store every value. Then instead of an exact median you use an approximate quantile: t-digest, HdrHistogram. Micrometer's Timer percentiles rely on exactly such histograms.
  • With many instances, you can't average medians; that's a mathematical error. You merge histograms, which are built for that.

That's why I ask "do we need the exact median, or is a p50 with 1% error enough?". For monitoring it's almost always the second.