Heapify
medium 16 minHeapify is how a binary heap repairs itself.
See it run
Sink a value down, bubble a value up, and build a whole heap bottom up in linear time.
Operations
Sift down
The root 10 is smaller than its children. Swap it with the larger child, again and again, until it beats both children or reaches a leaf.
Step 1 of 8
A broken root
- 100i
- 501
- 302
- 403
- 204
The array [10, 50, 30, 40, 20] is a max-heap everywhere except at the root. This is exactly what you get after a pop moves a small leaf to slot 0.
Step 1: A broken root
def sift_down(heap, i, n): while True: largest = i left, right = 2 * i + 1, 2 * i + 2 if left < n and heap[left] > heap[largest]: largest = left if right < n and heap[right] > heap[largest]: largest = right if largest == i: # parent beats both children return heap[i], heap[largest] = heap[largest], heap[i] i = largest # follow the value downh = [10, 50, 30, 40, 20]sift_down(h, 0, len(h))print(h) # [50, 40, 30, 10, 20]- Time
- O(log n)
- Space
- O(1)
- this run
- 4 comparisons, 2 swaps
- used by
- pop, build-heap, heap sort
Sift down compares with BOTH children and swaps with the LARGER one. Swap with the smaller child and the bigger one ends up below a smaller parent.
In the real world
The same heapify doing real jobs. Pick one and step through it.
Sift up is a light bubble in water: a newly inserted big value rises through smaller parents until it reaches its level.
Step 1 of 4
A calm heap
Max-heap [15, 13, 10, 9, 8, 5, 7]. A new value, 20, is about to be released at the bottom.
Step 1: A calm heap
import heapqheap = [-x for x in [15, 13, 10, 9, 8, 5, 7]] # heapq is a min-heap: negateheapq.heapify(heap)heapq.heappush(heap, -20) # append, then sift upprint(-heap[0]) # 20Common mistakes
The bugs interviewers watch for, with the fix beside each.
Starting build-heap at index 0
criticalSift down needs both subtrees to be heaps already. Going from the root forwards breaks that, and leaves need no work anyway. Start at the last parent, n // 2 - 1, and go backwards.
Wrongfor i in range(n // 2): # root first sift_down(a, i, n)Rightfor i in range(n // 2 - 1, -1, -1): # last parent first sift_down(a, i, n)Sifting up after removing the root
criticalAfter a pop the last leaf is moved to the root, so the broken spot is at the top. Sift up from index 0 does nothing. Use sift down after extract; sift up is for insert.
Wrongheap[0] = heap.pop()sift_up(heap, 0) # root has no parent: no-opRightlast = heap.pop()if heap: heap[0] = last sift_down(heap, 0, len(heap))Swapping with the wrong child
criticalIn a max-heap, swap with the LARGER child. Swapping 10 with 30 instead of 50 in [10, 50, 30] puts 30 above 50.
Wrongif heap[left] > heap[i]: # first child that beats i largest = leftRightlargest = iif left < n and heap[left] > heap[largest]: largest = leftif right < n and heap[right] > heap[largest]: largest = rightBuilding with n pushes
majorPushing values one by one sifts each one up and costs O(n log n). heapify on the whole list is O(n). Many candidates think build-heap is O(n log n); the bottom-up version is linear.
Wrongheap = []for x in data: heapq.heappush(heap, x) # O(n log n)Rightheap = list(data)heapq.heapify(heap) # O(n)Stopping after one swap
majorA swap can break the heap one level lower. Without the loop or recursive call, the value stops halfway: [10, 50, 30, 40, 20] would end as [50, 10, 30, 40, 20] with 10 above 40.
Wrongif largest != i: heap[i], heap[largest] = heap[largest], heap[i]Rightif largest != i: heap[i], heap[largest] = heap[largest], heap[i] sift_down(heap, largest, n)Expecting a max-heap from heapq
minorheapq is always a min-heap: heap[0] is the smallest. For a max-heap, store negated values (or (-priority, item) tuples) and negate again when you pop.
Wrongheapq.heapify(scores)best = scores[0] # the LOWEST scoreRighth = [-s for s in scores]heapq.heapify(h)best = -h[0] # the highest score
Interview tips
How to explain it
- Always clarify max-heap or min-heap first: the comparison direction changes.
- Draw the tree AND the array side by side; say parent (i - 1) // 2, children 2i + 1 and 2i + 2.
- Sift down after pop and in build-heap; sift up after push. Both O(log n).
Win the O(n) question
- Mention that build-heap is O(n): many candidates get this wrong.
- Half the nodes are leaves and cost nothing; only the root pays log n.
- Sum of h / 2^h converges to 2, so the total work is at most n.
Memory tricks
- BUBBLE: Bottom, Up or down, Big or little, Bump, Loop, End.
- Bubbles rise (sift up), stones sink (sift down).
- Build loop: n // 2 - 1 down to 0.
Watch out
- Sift down on a leaf returns at once; do not start build-heap at the leaves.
- heapq.heapify returns None and only makes min-heaps.
- Recursive sift down uses O(log n) stack; a loop is O(1).