Skip to lesson

Two heaps: running median

The two-heaps pattern partitions a data stream into two halves to compute the running median in O(1) time.

Balancing a max heap and a min heap

A running median is the median of the numbers seen so far, updated as each new number arrives; two heaps can maintain it in O(log n) per number.

The two-heaps technique keeps the lower half of the numbers in a max-heap and the upper half in a min-heap, so the median is always at one or both roots.

Java
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // smaller halfPriorityQueue<Integer> minHeap = new PriorityQueue<>();                           // larger half// Invariant: every value in maxHeap <= every value in minHeap, and the sizes differ// by at most 1, so the median is maxHeap.peek(), minHeap.peek() or their average

Every value in the lower half is smaller than or equal to every value in the upper half. The max-heap root is the largest of the lower half and the min-heap root is the smallest of the upper half, so both sit next to the median.

A naive solution appends each number and re-sorts, O(n log n) per query. Inserting with binary search still shifts elements in O(n).

Median calculation for odd and even counts

Keep the heaps balanced: the max-heap holds the same number of items as the min-heap, or one more. With an odd count the median is the max-heap root; with an even count it is the average of both roots.

Example 1 · Brute force: re-sort after every insert, O(n log n) per number, O(n) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int[] stream = {5, 15, 1, 3};        List<Integer> seen = new ArrayList<>();        for (int x : stream) {            seen.add(x);            Collections.sort(seen);                       // full sort on every new number            int n = seen.size();            double median = (n % 2 == 1)                ? seen.get(n / 2)                : (seen.get(n / 2 - 1) + seen.get(n / 2)) / 2.0;            System.out.println("after " + x + ": median " + median);        }    }}
Output
after 5: median 5.0
after 15: median 10.0
after 1: median 5.0
after 3: median 4.0

What this code does

  • Each new number is added and the whole list is sorted again, so the cost grows with every insert.
  • The median is then read from the middle of the sorted list.
  • The two-heaps version keeps the halves apart, so a new number costs only O(log n).

Example 2 · Optimal: two heaps, O(log n) per insert, O(1) median

Main.javaJava
import java.util.Collections;import java.util.PriorityQueue;
public class Main {    static class MedianFinder {        private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());        private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        public void addNum(int num) {            if (maxHeap.isEmpty() || num <= maxHeap.peek()) {                maxHeap.offer(num);            } else {                minHeap.offer(num);            }
            // Rebalance            if (maxHeap.size() > minHeap.size() + 1) {                minHeap.offer(maxHeap.poll());            } else if (minHeap.size() > maxHeap.size()) {                maxHeap.offer(minHeap.poll());            }        }
        public double findMedian() {            if (maxHeap.size() > minHeap.size()) {                return maxHeap.peek();            }            return (maxHeap.peek() + minHeap.peek()) / 2.0;        }    }
    public static void main(String[] args) {        MedianFinder mf = new MedianFinder();        mf.addNum(5);        System.out.println("Median after 5: " + mf.findMedian());        mf.addNum(15);        System.out.println("Median after 15: " + mf.findMedian());        mf.addNum(1);        System.out.println("Median after 1: " + mf.findMedian());        mf.addNum(3);        System.out.println("Median after 3: " + mf.findMedian());    }}
Output
Median after 5: 5.0
Median after 15: 10.0
Median after 1: 5.0
Median after 3: 4.0

What this code does

  • maxHeap tracks smaller values while minHeap tracks larger values.
  • Rebalancing guarantees size difference never exceeds one.
  • findMedian computes the result in constant O(1) time.
  • It is faster because the heaps keep only the middle ordered, so no insert ever sorts the whole stream.

Example 3 · Hand Tracing Heap States During Insertion

Main.javaJava
import java.util.Collections;import java.util.PriorityQueue;
public class Main {    public static void main(String[] args) {        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        int[] stream = {10, 20, 30};        for (int x : stream) {            if (maxHeap.isEmpty() || x <= maxHeap.peek()) maxHeap.offer(x);            else minHeap.offer(x);
            if (maxHeap.size() > minHeap.size() + 1) minHeap.offer(maxHeap.poll());            else if (minHeap.size() > maxHeap.size()) maxHeap.offer(minHeap.poll());
            double med = (maxHeap.size() > minHeap.size()) ? maxHeap.peek() : (maxHeap.peek() + minHeap.peek()) / 2.0;            System.out.println("Added " + x + " -> Median: " + med + " (Sizes: " + maxHeap.size() + "," + minHeap.size() + ")");        }    }}
Output
Added 10 -> Median: 10.0 (Sizes: 1,0)
Added 20 -> Median: 15.0 (Sizes: 1,1)
Added 30 -> Median: 20.0 (Sizes: 2,1)

What this code does

  • Adding 10 places it in maxHeap, giving median 10.0.
  • Adding 20 places it in minHeap, averaging to 15.0.
  • Adding 30 rebalances so maxHeap holds 2 items and minHeap holds 1 item.

To insert a number, offer it to the max-heap if it is at most the max-heap root, otherwise to the min-heap. Then rebalance: if the max-heap is more than one larger, move its root to the min-heap; if the min-heap is larger, move its root to the max-heap.

Insert and rebalance cost O(log n). Reading the median costs O(1).

Real world applications in live statistics

Production systems frequently monitor latency percentiles across millions of live network requests. The 50th percentile response time is the median latency of the server. Two heaps compute this running statistic continuously without storing historical logs in sorted order.

Example 4 · Live Latency Tracker Example

Main.javaJava
import java.util.Collections;import java.util.PriorityQueue;
public class Main {    static class LatencyMonitor {        PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder());        PriorityQueue<Integer> hi = new PriorityQueue<>();
        void recordLatencyMs(int ms) {            if (lo.isEmpty() || ms <= lo.peek()) lo.offer(ms);            else hi.offer(ms);            if (lo.size() > hi.size() + 1) hi.offer(lo.poll());            else if (hi.size() > lo.size()) lo.offer(hi.poll());        }
        double getP50() {            if (lo.size() > hi.size()) return lo.peek();            return (lo.peek() + hi.peek()) / 2.0;        }    }
    public static void main(String[] args) {        LatencyMonitor mon = new LatencyMonitor();        mon.recordLatencyMs(120);        mon.recordLatencyMs(80);        mon.recordLatencyMs(200);        mon.recordLatencyMs(95);
        System.out.println("Current P50 Latency: " + mon.getP50() + " ms");    }}
Output
Current P50 Latency: 107.5 ms

What this code does

  • Latency measurements stream into the monitor dynamically.
  • lo and hi heaps balance the incoming timings.
  • getP50 computes median response latency in O(1) time.

Financial exchanges track live mid-prices between bid and ask order flow. Streaming two-heap algorithms compute fair market value across trade updates in real time. IoT edge sensors deploy two heaps to filter high-frequency sensor noise on constrained hardware.

Next step

Check your understanding

10 quick questions