9. Heaps and Priority Queues
A complete binary tree stored in an array where every parent is smaller than its children (min-heap). The minimum is always at index 0; push and pop are O(log n).
How it works
A heap is stored level by level in a plain array: the children of index i are 2i + 1 and 2i + 2, and the parent is (i - 1) // 2. No pointers needed.
- push: append at the end, then sift up, swapping with the parent while smaller.
- pop: swap the root with the last item, remove it, then sift down the new root, swapping with the smaller child while bigger.
Python’s heapq module implements a min-heap on a list; negate values for a max-heap.
Diagram
graph TD
n_0["index 0: 3"]
n_0 -->|L| n_1
n_0 -->|R| n_2
n_2["index 2: 8"]
n_1["index 1: 5"]
n_1 -->|L| n_3
n_3["index 3: 9"]
Step-by-step trace
Input: Push 5, 3, 8, 1, 9, 2 into an empty min-heap, then pop twice.
| Operation | Returns | Swaps (moved up, moved down) | Array after |
|---|---|---|---|
| push(5) | - | none | [5] |
| push(3) | - | 3<->5 | [3, 5] |
| push(8) | - | none | [3, 5, 8] |
| push(1) | - | 1<->5, 1<->3 | [1, 3, 8, 5] |
| push(9) | - | none | [1, 3, 8, 5, 9] |
| push(2) | - | 2<->8 | [1, 3, 2, 5, 9, 8] |
| pop() | 1 | 2<->8 | [2, 3, 8, 5, 9] |
| pop() | 2 | 3<->9, 5<->9 | [3, 5, 8, 9] |
Result: Pops returned [1, 2]: always the current minimum. The diagram shows the final array [3, 5, 8, 9] as a tree.
Complexity
| Operation | Time | Space |
|---|---|---|
| Peek min | O(1) | O(1) |
| Push / pop | O(log n) | O(1) |
| Build heap from n items (heapify) | O(n) | O(1) |
| Top k of n items with a size-k heap | O(n log k) | O(k) |
Python reference implementation
class MinHeap:
def __init__(self):
self.a = []
def push(self, val):
self.a.append(val)
return self._sift_up(len(self.a) - 1)
def pop(self):
a = self.a
if not a:
raise IndexError("pop from empty heap")
a[0], a[-1] = a[-1], a[0]
smallest = a.pop()
swaps = self._sift_down(0) if a else []
return smallest, swaps
def _sift_up(self, i):
swaps = []
a = self.a
while i > 0:
parent = (i - 1) // 2
if a[i] >= a[parent]:
break
a[i], a[parent] = a[parent], a[i]
swaps.append((a[parent], a[i]))
i = parent
return swaps
def _sift_down(self, i):
swaps = []
a = self.a
n = len(a)
while True:
left, right, smallest = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
return swaps
a[i], a[smallest] = a[smallest], a[i]
swaps.append((a[i], a[smallest]))
i = smallest
Common mistakes and tips
- A heap is not sorted; only the root is guaranteed to be the minimum.
- For ‘k largest’, keep a min-heap of size k and pop whenever it grows past k.
- Push tuples like
(priority, counter, item)so ties never compare the items themselves.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Binary Search Trees | Next: Tries (Prefix Trees) |