AlgoViz

Heapify

medium 16 min

Heapify 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

  1. 100i
  2. 501
  3. 302
  4. 403
  5. 204
i = 0n = 5

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

15i=013i=110i=29i=38i=45i=57i=6

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])                                  # 20

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Starting build-heap at index 0

    critical

    Sift 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.

    Wrong
    for i in range(n // 2):                 # root first    sift_down(a, i, n)
    Right
    for i in range(n // 2 - 1, -1, -1):     # last parent first    sift_down(a, i, n)
  • Sifting up after removing the root

    critical

    After 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.

    Wrong
    heap[0] = heap.pop()sift_up(heap, 0)            # root has no parent: no-op
    Right
    last = heap.pop()if heap:    heap[0] = last    sift_down(heap, 0, len(heap))
  • Swapping with the wrong child

    critical

    In a max-heap, swap with the LARGER child. Swapping 10 with 30 instead of 50 in [10, 50, 30] puts 30 above 50.

    Wrong
    if heap[left] > heap[i]:      # first child that beats i    largest = left
    Right
    largest = iif left < n and heap[left] > heap[largest]: largest = leftif right < n and heap[right] > heap[largest]: largest = right
  • Building with n pushes

    major

    Pushing 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.

    Wrong
    heap = []for x in data:    heapq.heappush(heap, x)  # O(n log n)
    Right
    heap = list(data)heapq.heapify(heap)          # O(n)
  • Stopping after one swap

    major

    A 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.

    Wrong
    if largest != i:    heap[i], heap[largest] = heap[largest], heap[i]
    Right
    if largest != i:    heap[i], heap[largest] = heap[largest], heap[i]    sift_down(heap, largest, n)
  • Expecting a max-heap from heapq

    minor

    heapq 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.

    Wrong
    heapq.heapify(scores)best = scores[0]            # the LOWEST score
    Right
    h = [-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).