Binary heaps: array layout, sift up, sift down
A binary heap is a complete tree stored in an array where every parent is smaller than its children. Sift up after insert and sift down after removing the top.
The idea
A heap is a tree that lives in a plain array. The boxes below the tree are the same values in index order.
Each array cell is the twin of one tree node. Click a node and its cell lights up, so you never need pointers.
Intuition
Every parent is smaller than or equal to its children. So the smallest value always sits at the root.
Slots fill level by level, left to right. Index 1 has its parent at 0 and its children at 3 and 4.
For index i, the parent is (i - 1) / 2 rounded down and the children are 2i + 1 and 2i + 2. That formula replaces pointers.
A new value goes in the next free slot, which keeps the shape. It can break the order, so we repair it along one path.
Complexity
A heap with n values has about log2 n levels. One sift moves along one path, so it costs at most that many swaps.
1,000 values need 10 levels and 1,000,000 values need 20. Reading the minimum costs one look at index 0.
Push and pop cost O(log n). Peek is O(1), and the heap needs no memory beyond its array.
Pitfalls
When sifting down, swap with the smaller child. Swapping 8 with 4 leaves 3 below a bigger parent.
A heap is not sorted. Only the root is guaranteed smallest, and here 9 sits before 7 and 6.
Variations
A max-heap flips the rule: each parent is larger, so the biggest value sits at the root.
Heaps power priority queues: always serve the smallest key next, in O(log n) per operation.
Code
Pseudocode
push(heap, x)
append x to heap
i ← last index
while i > 0 and heap[i] < heap[parent(i)]
swap heap[i] and heap[parent(i)]
i ← parent(i)
pop(heap)
top ← heap[0]
move the last item to heap[0], shrink heap
i ← 0
loop
c ← the smaller child of i
if c does not exist or heap[i] ≤ heap[c]: stop
swap heap[i] and heap[c]
i ← c
return top
Python
def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0 and heap[i] < heap[(i - 1) // 2]:
p = (i - 1) // 2
heap[i], heap[p] = heap[p], heap[i]
i = p
def pop(heap):
top = heap[0]
last = heap.pop()
if heap:
heap[0] = last
i = 0
while True:
c = 2 * i + 1
if c >= len(heap): break
if c + 1 < len(heap) and heap[c + 1] < heap[c]: c += 1
if heap[i] <= heap[c]: break
heap[i], heap[c] = heap[c], heap[i]
i = c
return top
JavaScript
function push(heap, x) {
heap.push(x);
let i = heap.length - 1;
while (i > 0 && heap[i] < heap[(i - 1) >> 1]) {
const p = (i - 1) >> 1;
[heap[i], heap[p]] = [heap[p], heap[i]];
i = p;
}
}
function pop(heap) {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
let c = 2 * i + 1;
if (c >= heap.length) break;
if (c + 1 < heap.length && heap[c + 1] < heap[c]) c++;
if (heap[i] <= heap[c]) break;
[heap[i], heap[c]] = [heap[c], heap[i]];
i = c;
}
}
return top;
}
Java
static void push(List<Integer> heap, int x) {
heap.add(x);
int i = heap.size() - 1;
while (i > 0 && heap.get(i) < heap.get((i - 1) / 2)) {
int p = (i - 1) / 2;
Collections.swap(heap, i, p);
i = p;
}
}
static int pop(List<Integer> heap) {
int top = heap.get(0);
int last = heap.remove(heap.size() - 1);
if (!heap.isEmpty()) {
heap.set(0, last);
int i = 0;
while (true) {
int c = 2 * i + 1;
if (c >= heap.size()) break;
if (c + 1 < heap.size() && heap.get(c + 1) < heap.get(c)) c++;
if (heap.get(i) <= heap.get(c)) break;
Collections.swap(heap, i, c);
i = c;
}
}
return top;
}
Cost at a glance
| Access | O(1) min |
|---|---|
| Search | O(n) |
| Insert | O(log n) |
| Delete | O(log n) extract-min |
| Space | O(n) |
Practice problems (9)
Parent and child indices Warm-up
A heap stores its tree in an array, root at index 0, level by level. Complete heapIndices(i) so it returns [parent, left, right] for the node at index i.
The root has no parent: return -1 for it.
Which array is a min-heap? Warm-up
Each option is an array. Index 0 is the root, indices 1 and 2 are its children, and so on. Pick the array that is a valid min-heap.
Match the heap operation to its cost Warm-up
Match each operation on a binary min-heap of n values to its worst-case cost and the reason.
Insert into a heap Warm-up
The min-heap [2, 5, 3, 9, 7, 8] receives the value 1. It is placed in the next free slot first.
Answer each question before the step plays: first which node 1 meets, then the array after the sift up finishes.
Is this array a min-heap? Warm-up
Given an array values, return true if it is a valid min-heap: every value is at least as large as its parent. The parent of index i is (i - 1) / 2 rounded down.
An empty array and equal values are valid.
Extract the minimum Standard
Remove the minimum from the min-heap [2, 4, 3, 7, 5, 8, 6, 9]. The last value, 9, has already moved to the root.
Predict the first swap, then arrange the array once 9 has sunk to its place.
Implement push and pop Standard
Build a min-heap in an array and run a list of operations on it. A value x ≥ 0 means push x. The value -1 means pop the smallest value and report it, or report -1 when the heap is empty.
Return the reported values in order. Write sift up and sift down yourself; do not sort.
Spot the bug: sift down Standard
siftDown(heap, i) should move the value at index i down until the min-heap order holds below it. It returns the heap. It works for some heaps and fails for others.
Click the faulty line, then fix it.
Implement a max-heap with decrease-key Challenge
Run operations on a max-heap of items, each with an id and a key:
[0, id, key]inserts a new item.[1, id, key]lowers the key of a live item to the smallerkey.[2]removes the item with the largest key and reports itsid, or-1if the heap is empty.
Return the reported ids in order. All keys in one input are distinct. Decrease-key must run in O(log n).
Related topics
Next on the path: Building a heap in O(n)