Command Palette

Search for a command to run...

← All patterns

Pattern · Heaps

Two Heaps

Split values into a max-heap of the smaller half and a min-heap of the larger half to read the median instantly.

Time O(log n) per add, O(1) per median · Space O(n)

Taught in Module 18: Heaps and Priority Queues

Think of it like this

Lining up people by height into two rooms, short and tall, keeping the rooms balanced: the median is at the door between them.

Clues that point here

  • → Running median
  • → Median of a sliding window
  • → Balance two groups

Not this pattern when

  • ✕ You need any percentile other than the middle (use an order-statistic structure)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Two Heaps · template
PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());  // max-heap
PriorityQueue<Integer> high = new PriorityQueue<>();                            // min-heap

void add(int x) {
    low.offer(x);
    high.offer(low.poll());                   // keep every low <= every high
    if (high.size() > low.size()) low.offer(high.poll());   // low may hold one extra
}
double median() {
    return low.size() > high.size() ? low.peek() : (low.peek() + high.peek()) / 2.0;
}

Common versions

  • Find median from data stream
  • Sliding window median
  • IPO (maximise capital)

Practice problems with this pattern

Related patterns