Sub topic 6
Why the operations cost O(log n)
This chapter assumes you know Big-O notation, the array layout of a binary heap (children of index i at 2i+1 and 2i+2), and the sift up and sift down routines from the previous chapters. Here you will see where the O(log n) bound comes from and what it does and does not cover.
Height is the only variable
A heap is a complete binary tree. Every level is full except possibly the last, which fills from the left. That shape fixes the height. Level d holds at most 2^d nodes, so a tree with n nodes has height floor(log2 n).
| Items (n) | Height |
|---|---|
| 1 | 0 |
| 7 | 2 |
| 1,000 | 9 |
| 1,000,000 | 19 |
Doubling the data adds one level. A million items need at most 19 levels.
Cost of each operation
Sift up and sift down each move along a single path. They never branch.
- Push appends at the end, which is O(1) amortized for a Python list. Sift up then swaps with the parent at most once per level. That is at most
hswaps, wherehis the height. - Pop removes the root, moves the last item to the root, and sifts down. Each step compares the item with two children and swaps with the smaller one. That is at most
hsteps, each with a constant number of comparisons. - Peek reads
a[0], which is O(1).
So push and pop are O(log n) in the worst case. Both are cheap in practice, and a push often stops early. For random data, the average push needs only a constant number of swaps, because most nodes sit near the bottom and a new item rarely needs to climb far.
Measuring it
You can check the bound by counting swaps. This code uses the MinHeap shape from earlier, with a counter added to pop.
import heapq
import math
import random
def pop_with_count(a):
# Same logic as heapq.heappop, but returns the number of sift-down swaps.
top = a[0]
last = a.pop()
swaps = 0
if a:
a[0] = last
i, n = 0, len(a)
while True:
child = 2 * i + 1
if child >= n:
break
if child + 1 < n and a[child + 1] < a[child]:
child += 1
if a[i] <= a[child]:
break
a[i], a[child] = a[child], a[i]
i = child
swaps += 1
return top, swaps
for n in [1_000, 100_000]:
data = [random.random() for _ in range(n)]
heapq.heapify(data)
_, swaps = pop_with_count(data)
print(n, swaps, math.floor(math.log2(n)))The swap count never exceeds the printed height. A pop after a heapify typically comes close to it. The moved item came from the bottom level, so it is usually large and sinks nearly all the way back down.
Space cost
The array stores only the items. There are no child pointers and no node objects. A heap of n items uses O(n) space, and the extra space for push and pop is O(1) because the loops are iterative.
What the bound does not give you
- Searching for an arbitrary value is O(n). The heap property orders a parent against its children, not siblings or whole levels.
- Removing an arbitrary item costs O(n) to find it, then O(log n) to repair.
- Iterating in sorted order requires
npops, so O(n log n).
Exercise
A heap holds 1,000,000 items. About how many swaps can one pop perform at most, and why does adding one more item rarely change that number?
Show answer
At most 19, the height floor(log2 1,000,000). The height grows only when n crosses a power of two, so one extra item almost never adds a level.
Exercise
Why is finding the largest item in a min-heap O(n) and not O(log n)?
Show answer
The largest item can be any leaf, and leaves make up about half the array. Nothing in the heap property says which leaf, so you must scan them all.