Step 15 Heaps — Theory and Implementation
Heaps (Theory Video)
A heap is a complete binary tree stored in an array that maintains one promise: every parent is smaller than its children (min-heap) or larger (max-heap). That partial order is exactly what a priority queue needs — the extreme element is always at the root, reachable in O(1), with insert and extract in O(log n). This lesson covers the array representation, the two repair operations (bubble up and heapify down), and how building a heap from an array is O(n), not O(n log n).
Shape property + order property
A heap obeys two rules. Shape: it is a complete binary tree — every level full except possibly the last, which fills left to right — so its height is always floor(log n). Order: for a min-heap, each node's value is less than or equal to its children's; a max-heap reverses the comparison.
Notice what a heap does NOT promise: siblings are unordered relative to each other, and the tree is not sorted — an inorder traversal of a heap is not a sorted sequence. It is a weaker (and therefore cheaper to maintain) structure than a BST, optimised for exactly one query: give me the min (or max), repeatedly.
Array representation and index arithmetic
Because the tree is complete, it packs into an array with no gaps and no pointers. With 0-based indexing, node i has parent (i - 1) // 2 and children 2i + 1 and 2i + 2. The root sits at index 0, the last element at index n - 1, and the last internal node (parent) is at index n//2 - 1.
Getting these formulas wrong — usually by mixing in the 1-based versions (parent i//2, children 2i, 2i+1) — is the most frequent heap bug. Pick one convention per codebase and stick to it.
def parent(i): return (i - 1) // 2
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
# min-heap as a Python list: heap[0] is always the minimumThe two repair moves: bubble up and heapify down
Insert appends the new element at the end (preserving shape) and bubbles it up: while it is smaller than its parent, swap. Extract-min saves the root, moves the last element to the root (preserving shape), and heapifies down: repeatedly swap it with its smaller child until both children are larger or it reaches a leaf. Both moves travel one root-to-leaf path, so both are O(log n); peek is O(1).
Decrease-key / arbitrary updates use the same moves: if the value decreased, bubble up; if it increased, heapify down. Choosing the wrong direction is a classic bug — after an update you must consider which way the element can possibly be out of order.
def heapify_down(heap, i):
n = len(heap)
while True:
smallest = i
l, r = 2 * i + 1, 2 * i + 2
if l < n and heap[l] < heap[smallest]:
smallest = l
if r < n and heap[r] < heap[smallest]:
smallest = r
if smallest == i:
break
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0 and heap[(i - 1) // 2] > heap[i]:
p = (i - 1) // 2
heap[i], heap[p] = heap[p], heap[i]
i = pBuilding a heap in O(n), and heap sort
Inserting n elements one by one costs O(n log n). The faster build: copy the array as-is (shape property already satisfied by any array), then call heapify_down on every internal node from the last parent (index n//2 - 1) down to the root. Most nodes sit near the leaves and move down only a step or two, and the total work sums to O(n) — a result worth being able to sketch: sum over heights of (number of nodes) x (max sink distance) converges to about 2n swaps.
Heap sort reuses this: build a max-heap, then repeatedly swap the root (current maximum) to the end of the shrinking array and heapify down the reduced heap. Result: O(n log n) time, O(1) extra space, but not stable.
Complexity, uses, and common mistakes
Peek O(1); push and pop O(log n); build O(n); space O(n) in the array itself. Reach for a heap when the problem says top-K, k-th largest, merge many sorted streams, continuously extract min/max, or maintain a running median (two heaps). If you need arbitrary search or deletion of a named element, a heap is the wrong tool (those are O(n) without an index map).
Common mistakes: mixing 0-based and 1-based index formulas; heapifying only downward after an operation that requires bubbling up; assuming heap order implies sorted order when iterating; and in Python, forgetting that heapq is a min-heap only — negate values for max-heap behaviour, and use heapq.heapify for the O(n) build instead of pushing in a loop.
Key points
- Heap = complete binary tree in an array + parent-before-children order; only the root (the extreme) is guaranteed.
- 0-based indices: parent (i-1)//2, children 2i+1 and 2i+2 — never mix with the 1-based formulas.
- Insert = append + bubble up; extract = move last to root + heapify down. Both O(log n); peek O(1).
- Build by heapifying from the last parent down to the root: O(n) total, beating n inserts.
- Heaps answer 'extreme value, repeatedly' — top-K, k-way merge, streaming median — not search or sorted iteration.