Extract min/max
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Extracting the min or max takes the item off the top of the heap, which is the one to serve next, then fixes the heap quickly. It is the "next please" button of any priority system.
Practical use cases
- Web app: Serving the next call in a call centre. A support tool hands the next customer to a free agent. The waiting customers are in a heap by priority and wait time, so pressing "Next" removes the top and repairs the heap in a few swaps. Agents never wait for the app to search a long list. Customers get served in the right order.
- Web app: Picking the next order to dispatch. A delivery kitchen screen shows "Cook next". The most urgent order is taken off the top of the heap, and the remaining orders reorganise themselves. A rush of 500 orders does not slow the screen. Cooks always see the most urgent dish first.
- System: Dijkstra, CPU scheduling and order matching. Shortest-path search repeatedly takes the closest unvisited place off a heap. Operating systems pick the next task to run the same way, and trading engines take the best price off the top to match orders. All of them depend on the quick repair after each removal.
The story: Raju's Next-Order Bell
Raju's chai stall was famous, and orders came in with different brewing times: masala chai took 5 minutes, a plain cutting took 1, and a special kulhad took 8. Raju wanted the quickest order first, to keep the line moving.
His orders sat in a min heap. When he rang the bell for "next order", he grabbed the top of the tree. But then a throne was empty! Mira laughed: "Raju bhaiya, you cannot leave the top empty. A heap must stay full."
So Raju took the very last order from the bottom and sat it on the throne. It was surely too big for the top. So he let it sink: compare with the two children, swap with the smaller one, and repeat. After two or three swaps the next-quickest order floated to the top by itself.
That is extract min (or extract max in a max heap): remove the root, put the last item on top, sift it down. Do it repeatedly and the items come out in order, which is the secret behind priority queues and heap sort.
How to spot this problem, and where you need it
You repeatedly need to take the most important item out of a pile, serve it, and then immediately know who is next.
Signs you need it
- Your "get next" function sorts or scans the entire list every time.
- The statement says "remove and return the smallest or largest", "pop from a priority queue" or "serve the highest priority".
- Response time of the "next" action grows as the queue becomes long.
Where to use it in a project
- Call centre, support-ticket and dispatch screens with a "Next" action.
- Algorithms that process the best candidate first, such as shortest routes and task scheduling.
The solution
Save the top item to return. Move the last item of the array to the top and shrink the array by one. Then sink it: compare it with its children, swap with the better child if needed, and keep going until it fits. Return the saved item. The next best item is now on top.
Payoff: Before: scanning 20,000 waiting customers to pick one. After: one read plus about 14 swaps, with the next customer ready instantly.
Explain it like I am 8
The champion at the top of the pyramid steps off with a trophy. A kid from the very last spot is sent to stand on top. But they are too weak for the spot, so they step down, trading places with the stronger kid below, until the pyramid is steady again.
How it works, step by step
- Read the root: that is the answer (the smallest in a min heap, the biggest in a max heap).
- Move the last item of the array to the root and shrink the array by one.
- Sift down: compare it with its two children and swap with the more important child (smaller in a min heap, bigger in a max heap).
- Keep going until neither child beats it or it has no children.
- Return the value you saved in step 1.
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;
}
}
// Min heap: the smallest comes out first
$orders = new Heap();
foreach ([5, 3, 8, 1, 9, 2] as $minutes) $orders->push($minutes);
$served = [];
while ($orders->size() > 0) $served[] = $orders->pop(); // extract-min again and again
echo implode(' ', $served), PHP_EOL; // 1 2 3 5 8 9
// Max heap: just flip the question "who goes first?"
$scores = new Heap(fn($x, $y) => $x > $y);
foreach ([40, 95, 70, 85] as $s) $scores->push($s);
echo $scores->pop(), ' ', $scores->pop(), PHP_EOL; // 95 85JavaScript
// 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;
}
}
// Min heap: the smallest comes out first
const orders = new Heap();
[5, 3, 8, 1, 9, 2].forEach(minutes => orders.push(minutes));
const served = [];
while (orders.size() > 0) served.push(orders.pop()); // extract-min again and again
console.log(served.join(' ')); // 1 2 3 5 8 9
// Max heap: just flip the question "who goes first?"
const scores = new Heap((x, y) => x > y);
[40, 95, 70, 85].forEach(s => scores.push(s));
console.log(scores.pop() + ' ' + scores.pop()); // 95 85Java
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;
}
}
public static void main(String[] args) {
// Min heap: the smallest comes out first
Heap<Integer> orders = new Heap<>((x, y) -> x < y);
for (int minutes : new int[]{5, 3, 8, 1, 9, 2}) orders.push(minutes);
List<Integer> served = new ArrayList<>();
while (orders.size() > 0) served.add(orders.pop()); // extract-min again and again
System.out.println(served); // [1, 2, 3, 5, 8, 9]
// Max heap: just flip the question "who goes first?"
Heap<Integer> scores = new Heap<>((x, y) -> x > y);
for (int s : new int[]{40, 95, 70, 85}) scores.push(s);
System.out.println(scores.pop() + " " + scores.pop()); // 95 85
}
}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, bool) {
var zero T
if len(h.a) == 0 {
return zero, false
}
return h.a[0], true
}
// 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, bool) {
var zero T
if len(h.a) == 0 {
return zero, false
}
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, true
}
func main() {
// Min heap: the smallest comes out first
orders := &Heap[int]{before: func(x, y int) bool { return x < y }}
for _, minutes := range []int{5, 3, 8, 1, 9, 2} {
orders.Push(minutes)
}
var served []int
for orders.Size() > 0 {
v, _ := orders.Pop() // extract-min again and again
served = append(served, v)
}
fmt.Println(served) // [1 2 3 5 8 9]
// Max heap: just flip the question "who goes first?"
scores := &Heap[int]{before: func(x, y int) bool { return x > y }}
for _, s := range []int{40, 95, 70, 85} {
scores.Push(s)
}
first, _ := scores.Pop()
second, _ := scores.Pop()
fmt.Println(first, second) // 95 85
}Time: O(log n) · Extra space: O(1). Reading the top is O(1); removing it costs one sink along a single branch of a short tree.
Watch out for
- Removing the root and shifting the whole array left. That destroys the heap shape and costs O(n).
- Sinking towards the wrong child. In a min heap use the smaller child; in a max heap use the bigger one.
- Forgetting to shrink the size before sinking, so the old last item is still "seen" as a child.
Quick check
- After taking the root, what goes on top?
- The smaller child
- The last item of the array
- A new random item
- Extracting from a min heap again and again gives items in what order?
- Descending
- Random
- Ascending (smallest first)
- What does extract-max on a max heap return?
- The middle value
- The largest value (the root)
- The smallest value