Sub topic 5
Removing the minimum: sift down
This chapter assumes you know the heap property, the array layout with index arithmetic (children of i at 2*i + 1 and 2*i + 2), and the sift-up insertion from the previous chapter. You should also be comfortable reading O(log n).
The problem with removing the root
The minimum sits at index 0. If you delete it, you leave a hole at the top. Shifting every element left would cost O(n) and would also destroy the parent and child index arithmetic.
The fix keeps the tree complete. Take the last element of the array, which is always safe to remove, and move it into the root. The shape is now correct, but the value is probably too large for its position, so the heap property may be broken at the top. Sift down repairs this.
The sift-down procedure
- Remove the last element and save the root value to return.
- If the heap is not empty, put the removed last element at index 0.
- Compare the current element with its children and pick the smaller child.
- If the current element is less than or equal to that child, stop.
- Otherwise swap them and continue from the child's index.
You must swap with the smaller child, not just any child. If you swapped with the larger one, the smaller child would become the new parent of a larger sibling. That would break the heap property.
Implementation
def pop_min(a):
if not a:
raise IndexError("pop from empty heap")
top = a[0]
last = a.pop()
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
return top
heap = [1, 3, 2, 7, 4, 5]
print(pop_min(heap)) # 1
print(heap) # [2, 3, 5, 7, 4]
print(pop_min(heap)) # 2
print(heap) # [3, 4, 5, 7]In the first call, 5 moves to the root. Its children are 3 and 2, so it swaps with 2. At index 2 it has no children, so the loop ends.
Common errors
- Forgetting the empty-heap case after
pop(). If the heap had one element,a.pop()empties the list. Writinga[0] = lastthen raisesIndexError. Theif a:guard handles this. - Checking only the left child. The right child can be smaller. Test
child + 1 < nbefore reading it. - Using
<where<=is needed.a[i] <= a[child]stops on equal values. Using<for the stop test would swap equal elements for no reason. - Comparing against the wrong bound. After
pop()the length has changed, so computenafter the removal.
Cost
Each loop iteration moves the element down one level. A complete tree with n elements has about log₂ n levels, so the loop runs at most that many times. Each iteration does a constant number of comparisons and one swap. Extraction is therefore O(log n) in the worst case, with O(1) extra memory because everything happens in place.
| Operation | Time | Extra space |
|---|---|---|
| `peek` | O(1) | O(1) |
| `push` (sift up) | O(log n) | O(1) |
| `pop` (sift down) | O(log n) | O(1) |
The element taken from the end is usually large, because leaves tend to hold big values. It therefore often sinks all the way back down, so the typical cost is close to the worst case.
Exercise
Given the min-heap [2, 5, 3, 9, 6, 4], what does the array look like after one pop_min call, and which value is returned?
Show answer
The call returns 2. The last element, 4, moves to the root, giving [4, 5, 3, 9, 6]. Its children are 5 and 3, and 3 is smaller, so 4 swaps with 3, giving [3, 5, 4, 9, 6]. Index 2 has no children inside the array, so sifting stops. The final array is [3, 5, 4, 9, 6].