Heap properties
easy 16 minA binary heap is a complete binary tree in which every parent is greater than or equal to its children (max-heap) or less than or equal to them (min-heap).
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Complete shape, parent beats child, extreme at the root.
A family tree where every parent is taller than their own children. Walk up from anyone and people only get taller, so the grandparent at the top is the tallest. Cousins are never compared, so it is not a height ranking of the whole family.
Cheat sheet
- Shape
- complete binary tree
- Max-heap order
- parent ≥ children
- Min-heap order
- parent ≤ children
- Children of i
- 2i + 1 and 2i + 2
- Parent of i
- (i - 1) // 2
- Leaves
- n // 2 to n - 1
- Height
- floor(log2 n)
- Peek / push / pop
- O(1) / O(log n) / O(log n)
- Build / search
- O(n) / O(n)
Spot it when you see
- You repeatedly need the smallest or largest item.
- Words like top k, k-th largest, k closest or most frequent.
- Merging k sorted lists or streams.
- A running median over a stream.
- Processing items by priority, deadline or distance.
Tricks that stick
- HEAP: Highest (or lowest) Element Always at the Peak.
- Down: double plus one, double plus two. Up: minus one, halve, round down.
- Shape first, order second: every operation fixes the shape, then sifts along one path.
- Opposite heap for top-k: a min-heap keeps the k largest.
- Level k starts at index 2^k - 1: 0, 1, 3, 7, 15.
Do not forget
- Treating a heap as sorted, or expecting fast search.
- Checking only the root instead of every parent-child edge.
- Using / instead of // for the parent index in Python.
- Mixing 1-based formulas (2i, 2i + 1) with 0-based lists.
- Assuming heapq's heap[0] is the maximum: it is the minimum.
- Forgetting the right child may not exist (check 2i + 2 < n).