Two Heaps

A max-heap for the lower half and a min-heap for the upper half keep the median at the two roots: O(log n) to add a value, O(1) to read the median, plus the sliding-window and IPO variants.

Overview

The two-heaps pattern splits a set of numbers into a lower half and an upper half. A max-heap holds the lower half, so its root is the largest small value. A min-heap holds the upper half, so its root is the smallest large value. The median of the whole set is then always at one root or the other, or the average of both.

The pattern answers one question well: what is the middle of the data right now, while values keep arriving? Sorting after every insert costs O(n log n) each time; a sorted list costs O(n) per insert because it shifts elements. Two heaps cost O(log n) per insert and O(1) per median query.

The two invariants

An invariant is a rule that must be true after every operation. Two heaps keep two of them, and the median is read from the roots only because both hold.

  • Order: every value in the lower heap is at most every value in the upper heap. This is what makes the two roots the two values next to the middle.
  • Size: the heaps are the same size, or the lower one has one extra. This puts the middle at a root, not somewhere inside a heap.

If either rule breaks, the roots stop being the median. Both must hold after every insert, so the next question is how to add a value without breaking either.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio