Two-heaps technique
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The two-heaps technique uses a min heap and a max heap side by side, so you can always reach the best item in two groups at once. It solves problems like running medians and "pick the best project you can afford as your budget grows".
Practical use cases
- Web app: Picking projects as your budget grows. A funding app has projects with a cost and a profit, and the investor can only start projects they can afford. One heap holds projects ordered by cost, another holds affordable ones ordered by profit. Each round moves newly affordable projects across and picks the best, so a list of 10,000 projects is handled quickly.
- Web app: Task scheduler with start times. A scheduler has jobs that become available at different times, and each time a worker is free it must pick the most valuable available job. A heap of not-yet-available jobs feeds a heap of available ones. Workers are never idle while a job is waiting.
- System: Running medians and sliding windows. Systems tracking a median over a moving window of readings keep the lower half in one heap and the upper half in another. Matchmaking and monitoring tools use this to know the middle value at any moment. Old readings leave one heap as new ones enter another.
The story: Zoya's Two Notice Boards
Zoya had saved nothing, but she had five ideas for small side projects: stitching bags, selling kites, repairing bicycles... Each needed some start-up money (the cost) and would earn some profit. She could finish only three projects before her exams. Her puzzle: which projects, in which order, leave her richest?
Mira noticed two questions in every round. First: "Which projects can I afford right now?" Second: "Among those, which gives the biggest profit?" Two questions, two different orderings. Mira said, "Use two notice boards!"
The waiting board keeps all projects with the cheapest start-up cost on top (a min heap by cost). The ready board keeps affordable projects with the biggest profit on top (a max heap by profit). Each round: move every project Zoya can now afford from waiting to ready, then take the most profitable one from the ready board. Her money grows, unlocking more projects.
That is the two-heaps technique: when a problem needs two different "best" answers at once, give each its own heap and let items travel between them. The running median is the other famous use. Here the two heaps split the items by who is eligible instead of by who is smaller.
How to spot this problem, and where you need it
Your data has two groups, such as cheap and expensive or not ready and ready, and you must always know the best item from each group as things move between them.
Signs you need it
- You need the minimum of one group and the maximum of another at the same time.
- Items become eligible over time, such as projects that unlock as your capital grows, and you must pick the best eligible one.
- The task mentions "median", "IPO", "maximise capital" or "split into two halves".
Where to use it in a project
- Schedulers and planners where jobs, projects or offers unlock at certain times or budgets.
- Live statistics, such as medians over a stream or a moving window of the latest values.
The solution
Choose two heaps matching the two groups, for example a min heap on cost for items you cannot yet afford and a max heap on profit for items you can. At each step, move everything now eligible from the first heap to the second, then take the best from the second. Repeat until you have done the needed number of picks.
Payoff: Before: re-scanning all 10,000 projects after each pick. After: each project moves between heaps once, and each pick is a quick heap operation.
Explain it like I am 8
Two baskets. In basket one are the things you cannot buy yet, with the cheapest on top. As your pocket money grows, you move things you can now afford into basket two. From basket two you always pick the one that gives you the most fun. Two baskets, two kinds of "best".
How it works, step by step
- Decide the two questions the problem asks, for example "who is eligible?" and "who is best among the eligible?".
- Give each question its own heap: one ordered by the eligibility key (min heap by cost), one by the score (max heap by profit).
- Each round, move everything that has just become eligible from the first heap to the second.
- Then pop the best from the second heap and apply it (add the profit).
- Repeat for the allowed number of rounds, or stop early when the ready heap is empty.
The code in four languages
PHP
<?php
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before($x, $y) answers: "does x belong closer to the top than y?" (default = min-heap)
class Heap {
private array $a = [];
private $before;
public function __construct(?callable $before = null) {
$this->before = $before ?? fn($x, $y) => $x < $y;
}
public function size(): int { return count($this->a); }
public function peek() { return $this->a[0] ?? null; }
public function push($v): void { // put it at the bottom, then climb
$this->a[] = $v;
$i = count($this->a) - 1;
while ($i > 0) {
$p = intdiv($i - 1, 2);
if (!($this->before)($this->a[$i], $this->a[$p])) break;
[$this->a[$i], $this->a[$p]] = [$this->a[$p], $this->a[$i]];
$i = $p;
}
}
public function pop() { // take the top, put the last one on top, sink it
if (count($this->a) === 0) return null;
$top = $this->a[0];
$last = array_pop($this->a);
$n = count($this->a);
if ($n > 0) {
$this->a[0] = $last;
$i = 0;
while (true) {
$l = 2 * $i + 1; $r = $l + 1; $best = $i;
if ($l < $n && ($this->before)($this->a[$l], $this->a[$best])) $best = $l;
if ($r < $n && ($this->before)($this->a[$r], $this->a[$best])) $best = $r;
if ($best === $i) break;
[$this->a[$i], $this->a[$best]] = [$this->a[$best], $this->a[$i]];
$i = $best;
}
}
return $top;
}
}
// Pick at most $k projects to end up with the most money.
// Waiting heap: cheapest cost on top. Ready heap: biggest profit on top.
function maximizeCapital(int $k, int $money, array $profits, array $costs): int {
$waiting = new Heap(fn($x, $y) => $x[0] < $y[0]); // entries are [cost, profit]
$ready = new Heap(fn($x, $y) => $x > $y); // entries are profits
foreach ($profits as $i => $p) $waiting->push([$costs[$i], $p]);
for ($round = 0; $round < $k; $round++) {
while ($waiting->size() > 0 && $waiting->peek()[0] <= $money) {
$ready->push($waiting->pop()[1]); // newly affordable: move to the ready board
}
if ($ready->size() === 0) break; // nothing affordable: stop early
$money += $ready->pop(); // do the most profitable project
}
return $money;
}
echo maximizeCapital(3, 0, [2, 6, 4, 9, 3], [0, 3, 1, 5, 2]), PHP_EOL; // 15
echo maximizeCapital(2, 0, [5, 8], [1, 2]), PHP_EOL; // 0 (nothing affordable)JavaScript
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?" (default = min-heap)
class Heap {
constructor(before = (x, y) => x < y) { this.a = []; this.before = before; }
size() { return this.a.length; }
peek() { return this.a[0]; }
push(v) { // put it at the bottom, then climb
const a = this.a; a.push(v);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.before(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]]; i = p;
}
}
pop() { // take the top, put the last one on top, sink it
const a = this.a;
if (a.length === 0) return null;
const top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1; let best = i;
if (l < a.length && this.before(a[l], a[best])) best = l;
if (r < a.length && this.before(a[r], a[best])) best = r;
if (best === i) break;
[a[i], a[best]] = [a[best], a[i]]; i = best;
}
}
return top;
}
}
// Pick at most k projects to end up with the most money.
// Waiting heap: cheapest cost on top. Ready heap: biggest profit on top.
function maximizeCapital(k, money, profits, costs) {
const waiting = new Heap((x, y) => x[0] < y[0]); // entries are [cost, profit]
const ready = new Heap((x, y) => x > y); // entries are profits
profits.forEach((p, i) => waiting.push([costs[i], p]));
for (let round = 0; round < k; round++) {
while (waiting.size() > 0 && waiting.peek()[0] <= money) {
ready.push(waiting.pop()[1]); // newly affordable: move to the ready board
}
if (ready.size() === 0) break; // nothing affordable: stop early
money += ready.pop(); // do the most profitable project
}
return money;
}
console.log(maximizeCapital(3, 0, [2, 6, 4, 9, 3], [0, 3, 1, 5, 2])); // 15
console.log(maximizeCapital(2, 0, [5, 8], [1, 2])); // 0 (nothing affordable)Java
import java.util.*;
import java.util.function.BiPredicate;
public class Main {
// A heap lives in a plain list. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
static class Heap<T> {
private final List<T> a = new ArrayList<>();
private final BiPredicate<T, T> before;
Heap(BiPredicate<T, T> before) { this.before = before; }
int size() { return a.size(); }
T peek() { return a.isEmpty() ? null : a.get(0); }
void push(T v) { // put it at the bottom, then climb
a.add(v);
int i = a.size() - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (!before.test(a.get(i), a.get(p))) break;
Collections.swap(a, i, p);
i = p;
}
}
T pop() { // take the top, put the last one on top, sink it
if (a.isEmpty()) return null;
T top = a.get(0);
T last = a.remove(a.size() - 1);
int n = a.size();
if (n > 0) {
a.set(0, last);
int i = 0;
while (true) {
int l = 2 * i + 1, r = l + 1, best = i;
if (l < n && before.test(a.get(l), a.get(best))) best = l;
if (r < n && before.test(a.get(r), a.get(best))) best = r;
if (best == i) break;
Collections.swap(a, i, best);
i = best;
}
}
return top;
}
}
record Project(int cost, int profit) {}
// Pick at most k projects to end up with the most money.
// Waiting heap: cheapest cost on top. Ready heap: biggest profit on top.
static int maximizeCapital(int k, int money, int[] profits, int[] costs) {
Heap<Project> waiting = new Heap<>((x, y) -> x.cost() < y.cost());
Heap<Integer> ready = new Heap<>((x, y) -> x > y); // entries are profits
for (int i = 0; i < profits.length; i++) waiting.push(new Project(costs[i], profits[i]));
for (int round = 0; round < k; round++) {
while (waiting.size() > 0 && waiting.peek().cost() <= money) {
ready.push(waiting.pop().profit()); // newly affordable: move to the ready board
}
if (ready.size() == 0) break; // nothing affordable: stop early
money += ready.pop(); // do the most profitable project
}
return money;
}
public static void main(String[] args) {
System.out.println(maximizeCapital(3, 0, new int[]{2, 6, 4, 9, 3}, new int[]{0, 3, 1, 5, 2})); // 15
System.out.println(maximizeCapital(2, 0, new int[]{5, 8}, new int[]{1, 2})); // 0 (nothing affordable)
}
}Go
package main
import "fmt"
// A heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
type Heap[T any] struct {
a []T
before func(x, y T) bool
}
func (h *Heap[T]) Size() int { return len(h.a) }
func (h *Heap[T]) Peek() T { return h.a[0] }
// Push puts it at the bottom, then climbs.
func (h *Heap[T]) Push(v T) {
h.a = append(h.a, v)
i := len(h.a) - 1
for i > 0 {
p := (i - 1) / 2
if !h.before(h.a[i], h.a[p]) {
break
}
h.a[i], h.a[p] = h.a[p], h.a[i]
i = p
}
}
// Pop takes the top, puts the last one on top, and sinks it.
func (h *Heap[T]) Pop() T {
top := h.a[0]
last := h.a[len(h.a)-1]
h.a = h.a[:len(h.a)-1]
n := len(h.a)
if n > 0 {
h.a[0] = last
i := 0
for {
l, r, best := 2*i+1, 2*i+2, i
if l < n && h.before(h.a[l], h.a[best]) {
best = l
}
if r < n && h.before(h.a[r], h.a[best]) {
best = r
}
if best == i {
break
}
h.a[i], h.a[best] = h.a[best], h.a[i]
i = best
}
}
return top
}
type project struct{ cost, profit int }
// maximizeCapital picks at most k projects to end up with the most money.
// Waiting heap: cheapest cost on top. Ready heap: biggest profit on top.
func maximizeCapital(k, money int, profits, costs []int) int {
waiting := &Heap[project]{before: func(x, y project) bool { return x.cost < y.cost }}
ready := &Heap[int]{before: func(x, y int) bool { return x > y }} // entries are profits
for i, p := range profits {
waiting.Push(project{costs[i], p})
}
for round := 0; round < k; round++ {
for waiting.Size() > 0 && waiting.Peek().cost <= money {
ready.Push(waiting.Pop().profit) // newly affordable: move to the ready board
}
if ready.Size() == 0 { // nothing affordable: stop early
break
}
money += ready.Pop() // do the most profitable project
}
return money
}
func main() {
fmt.Println(maximizeCapital(3, 0, []int{2, 6, 4, 9, 3}, []int{0, 3, 1, 5, 2})) // 15
fmt.Println(maximizeCapital(2, 0, []int{5, 8}, []int{1, 2})) // 0 (nothing affordable)
}Time: O((n + k) log n) · Extra space: O(n). Each project moves from the waiting heap to the ready heap at most once, and each of the k rounds pops one best project.
Watch out for
- Trying to use a single heap (or a single sort) for both questions. The orderings are different, which is why two heaps are needed.
- Forgetting the while loop that moves all newly affordable projects, not just one.
- Not handling the case where nothing is affordable. Break out instead of popping from an empty heap.
Quick check
- When is the two-heaps technique a good idea?
- Only for medians
- When two different "best" answers are needed at the same time
- When the data is already sorted
- In Zoya's problem, the waiting heap is ordered by...
- Profit, biggest first
- Cost, smallest first
- Name
- After finishing a project, why do we check the waiting heap again next round?
- Because heaps forget items
- To sort the profits
- Money grew, so more projects may be affordable