AlgoViz

Two heaps

medium 22 min

The two heaps pattern keeps a max-heap for the smaller half of the values and a min-heap for the larger half.

Video lesson · Chapter 1 of 8

Live ferry gauge

0:00 / 5:51

Two heaps in 75 seconds

1:17Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Route by value. A new value joins the smaller half (a max-heap) if it is no bigger than that half's top, otherwise the larger half (a min-heap)

Understand it

Start here

Where priority queues left off

  • You already know heaps

    Push and pop in O(log⁡n)O(\log n), peek in O(1)O(1), and Python's heapq is min-only, so a max-heap stores negated values. Recap in heap operations.

  • You have seen the running median

    Priority queues sketched it in one section. This page takes it apart: the invariants, each method, the proofs and three harder problems.

  • What is new here

    Rebalancing proofs, sliding window medians with lazy deletion, any percentile, and IPO, where two heaps on different keys drive a greedy choice.

The problem: numbers arrive one at a time, and after any of them someone may ask for the median, the middle value. Sorting everything each time works but repeats almost all of the work. Two heaps keep the data split around the middle permanently, so each new value costs only a few heap steps.

The median of n sorted values

a1≤a2≤⋯≤an,median={a(n+1)/2n oddan/2+an/2+12n evena_1 \le a_2 \le \dots \le a_n, \qquad \text{median} = \begin{cases} a_{(n+1)/2} & n \text{ odd} \\[4pt] \dfrac{a_{n/2} + a_{n/2+1}}{2} & n \text{ even} \end{cases}
Only one or two values matter: the largest of the lower half and the smallest of the upper half. That is exactly what a max-heap and a min-heap hand you at their roots.

The idea

Split the values into two halves

Picture a deck of cards split into two piles. The left pile holds the smaller cards with the largest of them on top; the right pile holds the bigger cards with the smallest on top. With 1 to 10 dealt out, the left top is 5 and the right top is 6, so the median is (5+6)/2=5.5(5 + 6) / 2 = 5.5 without looking at any other card.

Two heaps facing each other

low is a max-heap of the smaller half, high is a min-heap of the larger half. Their roots face each other across the middle.
Life of one value
  1. 1Arrivex comes in from the stream
  2. 2Comparex against the top of low
  3. 3Join a halfpush into low or high
  4. 4Maybe crossone root moves if sizes drift
  5. 5Roots answermedian from the tops

Invariants

The two rules that make it work

Order invariant

max⁡(low)  ≤  min⁡(high)\max(\text{low}) \;\le\; \min(\text{high})
Every value in low is no bigger than every value in high. Routing each new value by comparing it with the top of low keeps this true.

Balance invariant

0  ≤  ∣low∣−∣high∣  ≤  10 \;\le\; |\text{low}| - |\text{high}| \;\le\; 1
The sizes are equal, or low holds one extra. Together with order, this pins the middle value or values to the two roots.

Median from the roots

median={max⁡(low)∣low∣>∣high∣max⁡(low)+min⁡(high)2∣low∣=∣high∣\text{median} = \begin{cases} \max(\text{low}) & |\text{low}| > |\text{high}| \\[4pt] \dfrac{\max(\text{low}) + \min(\text{high})}{2} & |\text{low}| = |\text{high}| \end{cases}

Method 1

add: route by value, then rebalance

add(x)

Routing protects the order invariant; the size check protects the balance invariant. At most one root crosses per add.
Python
import heapqclass MedianFinder:    def __init__(self):        self.low = []    # max-heap of the smaller half (stored negated)        self.high = []   # min-heap of the larger half    def add(self, x):        if not self.low or x <= -self.low[0]:            heapq.heappush(self.low, -x)        else:            heapq.heappush(self.high, x)        self.rebalance()    def rebalance(self):        if len(self.low) > len(self.high) + 1:            heapq.heappush(self.high, -heapq.heappop(self.low))        elif len(self.high) > len(self.low):            heapq.heappush(self.low, -heapq.heappop(self.high))    def median(self):        if len(self.low) > len(self.high):            return -self.low[0]        return (-self.low[0] + self.high[0]) / 2mf = MedianFinder()for x in [41, 35, 62, 4, 97, 108]:    mf.add(x)    print(x, "->", mf.median())   # 41, 38.0, 41, 38.0, 41, 51.5
low stores negated values because heapq is a min-heap. The stream is 41, 35, 62, 4, 97, 108.
Edit and run it in your browser

Trace of the stream 41, 35, 62, 4, 97, 108

addrouted torebalancelow (as a heap)high (as a heap)median
41low (empty)none[41][]41
35low, 35≤4135 \le 4141 to high[35][41]38.0
62high, 62>3562 > 3541 to low[41, 35][62]41
4low, 4≤414 \le 4141 to high[35, 4][41, 62]38.0
97high, 97>3597 > 3541 to low[41, 4, 35][62, 97]41
108high, 108>41108 > 41none[41, 4, 35][62, 97, 108]51.5
41 sits right on the boundary, so it is the value that keeps crossing. Sorted check: 4, 35, 41, 62, 97, 108.

Method 2

rebalance: why one move is enough

The gap argument

d=∣low∣−∣high∣∈{0,1}  →push  d∈{−1,0,1,2}  →one move  d∈{0,1}d = |\text{low}| - |\text{high}| \in \{0, 1\} \;\xrightarrow{\text{push}}\; d \in \{-1, 0, 1, 2\} \;\xrightarrow{\text{one move}}\; d \in \{0, 1\}
A push changes the gap by 1; moving a root changes it by 2. So −1-1 becomes 11 and 22 becomes 00: an if, never a while.

Moving a root never breaks the order invariant either. The max of low is the largest small value, so placing it in high keeps it no bigger than anything else there; the same holds for the min of high moving down. Sorted input (1, 2, 3, 4, 5) sends every value to high and forces a move on every other add; reversed input sends every value to low. Either way the halves end up as low = {1, 2, 3}, high = {4, 5}.

Method 3

findMedian: read the two roots

findMedian()

Two size reads and at most two root reads: O(1)O(1). Guard against an empty stream before reading low[0].

The three cases

sizesmedianexample
∣low∣=∣high∣|\text{low}| = |\text{high}|average of both tops[41, 4, 35] and [62, 97, 108]: (41+62)/2=51.5(41 + 62)/2 = 51.5
∣low∣=∣high∣+1|\text{low}| = |\text{high}| + 1top of low[41, 4, 35] and [62, 97]: 41
∣high∣=∣low∣+1|\text{high}| = |\text{low}| + 1top of high (only if your convention allows it)never happens with the rebalance above

Cost

O(log n) to add, O(1) to read

One add

Tadd(n)≤log⁡2n⏟push+2log⁡2n⏟pop + push of a move+O(1)=O(log⁡n),Tmedian=O(1)T_{\text{add}}(n) \le \underbrace{\log_2 n}_{\text{push}} + \underbrace{2\log_2 n}_{\text{pop + push of a move}} + O(1) = O(\log n), \qquad T_{\text{median}} = O(1)
Each heap holds about n/2n/2 values, so every heap operation is at most log⁡2n\log_2 n sift levels. Space is O(n)O(n): every value is stored once.

A whole stream, versus re-sorting

∑i=1nlog⁡i=log⁡n!=Θ(nlog⁡n)vs∑i=1nilog⁡i=Θ(n2log⁡n)\sum_{i=1}^{n} \log i = \log n! = \Theta(n \log n) \qquad \text{vs} \qquad \sum_{i=1}^{n} i \log i = \Theta(n^2 \log n)
Answering after every value with two heaps costs the same as sorting once. Re-sorting after every value is a factor of nn worse.

Ways to answer a median after every value

approachaddmediannotes
Sort after each addO(1)O(1)O(nlog⁡n)O(n \log n)simplest, quadratic overall
bisect.insort into a listO(n)O(n) shiftO(1)O(1)fine for small n, shifting dominates
Quickselect per queryO(1)O(1)O(n)O(n) averagegood when queries are rare
Two heapsO(log⁡n)O(\log n)O(1)O(1)the standard answer
Sorted container or order-statistic treeO(log⁡n)O(\log n)O(log⁡n)O(\log n)also supports delete and any rank
Counting array, values in 0..100O(1)O(1)O(100)O(100)the classic bounded-range follow-up

Pattern

Sliding window median with lazy deletion

Now report the median of every window of size kk, as in a fixed sliding window. Each slide adds one value and removes one. Adding is easy; removing is the hard part, because a heap can only remove its root cheaply. The fix is lazy deletion: record the leaving value in a gone counter, adjust a live-size counter, and actually pop it only when it reaches a root.

One slide of the window

A value that leaves while buried in the middle stays in the array, marked dead, until it surfaces. The roots are always live.
Python
import heapqdef window_medians(nums, k):    low, high = [], []        # max-heap (negated), min-heap    gone = {}                 # value -> copies waiting to be deleted    live = [0, 0]             # real sizes of low and high    def prune(h, sign):       # pop dead values sitting on top        while h and gone.get(sign * h[0], 0):            gone[sign * h[0]] -= 1            heapq.heappop(h)    def balance():        if live[0] > live[1] + 1:            heapq.heappush(high, -heapq.heappop(low))            live[0] -= 1; live[1] += 1            prune(low, -1)        elif live[1] > live[0]:            heapq.heappush(low, -heapq.heappop(high))            live[1] -= 1; live[0] += 1            prune(high, 1)    out = []    for i, x in enumerate(nums):        if not low or x <= -low[0]:            heapq.heappush(low, -x); live[0] += 1        else:            heapq.heappush(high, x); live[1] += 1        if i >= k:            y = nums[i - k]            gone[y] = gone.get(y, 0) + 1            if y <= -low[0]:                live[0] -= 1                prune(low, -1)            else:                live[1] -= 1                prune(high, 1)        balance()        if i >= k - 1:            out.append(-low[0] if k % 2 else (-low[0] + high[0]) / 2)    return outprint(window_medians([1, 3, -1, -3, 5, 3, 6, 7], 3))   # [1, -1, -1, 3, 5, 6]
For [1, 3, -1, -3, 5, 3, 6, 7] and k = 3 the medians are 1, -1, -1, 3, 5, 6. When -3 leaves it is buried under 3, so it stays as dead weight until later.
Edit and run it in your browser

Pattern

IPO: maximize capital

You start with capital ww and may finish at most kk projects. Project ii needs capital cic_i to start and adds profit pip_i when done; capital is never spent, only gained. Two heaps on different keys solve it: locked, a min-heap by capital, releases projects as soon as you can afford them, and ready, a max-heap by profit, hands you the best one you can start now.

The two-heaps greedy

Every project crosses from locked to ready at most once and leaves ready at most once: O(nlog⁡n)O(n \log n) overall.

Why the greedy choice is safe

p∗=max⁡{ pi:ci≤w }  ⇒  w+p∗≥w+pj  ⇒  { i:ci≤w+pj }⊆{ i:ci≤w+p∗ }p^{*} = \max\{\,p_i : c_i \le w\,\} \;\Rightarrow\; w + p^{*} \ge w + p_j \;\Rightarrow\; \{\,i : c_i \le w + p_j\,\} \subseteq \{\,i : c_i \le w + p^{*}\,\}
Exchange argument: taking the largest affordable profit leaves you at least as rich as any other choice, so every project still open to the other choice is open to you. Swap the first differing pick of an optimal plan for p∗p^{*} and it is no worse.
Python
import heapqdef max_capital(k, w, profits, capital):    locked = list(zip(capital, profits))   # min-heap by capital    heapq.heapify(locked)    ready = []                             # max-heap by profit (negated)    for _ in range(k):        while locked and locked[0][0] <= w:            c, p = heapq.heappop(locked)            heapq.heappush(ready, -p)        if not ready:            break                          # nothing affordable: stop early        w += -heapq.heappop(ready)    return wprint(max_capital(3, 0, [1, 2, 3, 5], [0, 1, 1, 4]))   # 9print(max_capital(2, 0, [1, 2, 3], [0, 1, 1]))         # 4
Capital (0, 1, 1, 4) and profit (1, 2, 3, 5) with k = 3: take 1, then 3, then 5, finishing with 9.
Edit and run it in your browser

Generalise

Beyond the median: any percentile

The median is only the 50th percentile. To track the pp-th percentile of a stream, keep the same two heaps but change the target size of low: instead of half the values it holds the smallest ⌈pn/100⌉\lceil pn/100 \rceil of them, and the answer is its root. The old intuition that two heaps only do medians is too narrow; any fixed percentile works.

Target size for the p-th percentile (nearest rank)

∣low∣=t(n)=⌈p⋅n100⌉,answer=max⁡(low),t(n+1)−t(n)∈{0,1}|\text{low}| = t(n) = \left\lceil \frac{p \cdot n}{100} \right\rceil, \qquad \text{answer} = \max(\text{low}), \qquad t(n+1) - t(n) \in \{0, 1\}
The target grows by at most one per value, so one move per add still restores it. For p = 90 low holds 90 percent of the values and high holds the top 10 percent.

Decide

When to reach for two heaps

Choosing a tool for middle values

Perfect for

  • Median of a data stream
  • Sliding window median (with lazy deletion)
  • A fixed percentile of a stream, such as p90
  • IPO-style greedy: unlock by one key, choose by another
  • Scheduling with free and busy pools, such as meeting rooms III

Not ideal for

  • Needing all values in sorted order
  • Arbitrary rank queries that change every call (use an order-statistic tree)
  • Very tight memory on huge streams (use an approximate sketch)
  • Frequent deletions of arbitrary values outside a window

Classic problems

problemlevelkey insight
295. Find Median from Data StreamHardthe core pattern: route, rebalance, read roots
480. Sliding Window MedianHardtwo heaps plus lazy deletion and live counters
502. IPOHardmin-heap by capital, max-heap by profit
436. Find Right IntervalMediumheaps by end and by start, popped in step (binary search also works)
2402. Meeting Rooms IIIHardfree rooms by number, busy rooms by end time

Recap

Key takeaways

Key points

  • low is a max-heap of the smaller half, high is a min-heap of the larger half.
  • Order: max⁡(low)≤min⁡(high)\max(\text{low}) \le \min(\text{high}). Balance: low has the same size as high or one more.
  • add routes by comparing with the top of low, then moves at most one root: O(log⁡n)O(\log n).
  • The median is the top of low, or the average of both tops: O(1)O(1). Use / 2, not // 2.
  • Over a stream, two heaps cost Θ(nlog⁡n)\Theta(n \log n) in total; re-sorting each time costs Θ(n2log⁡n)\Theta(n^2 \log n).
  • Sliding window median: mark leaving values as gone, prune only at the roots, balance on live counts.
  • IPO: a min-heap by capital unlocks projects, a max-heap by profit picks the best; greedy is safe because capital only grows.
  • Any fixed percentile works by making low hold ⌈pn/100⌉\lceil pn/100 \rceil values.

Sources