AlgoViz

Heap operations

medium 18 min

A binary heap supports insert (add at the end, sift up), extract (move the last value to the root, sift down) and peek (read the root).

See it run

Every heap operation is a small edit at the root or the end of the array, followed by one sift along a single root-to-leaf path.

Operations

Insert (sift up)

Add 7 to the max-heap [10, 5, 3, 4, 1]: put it in the next free slot, then swap it with its parent while it is bigger. Then a second case where the new value climbs all the way to the root.

Step 1 of 11

A max-heap in an array

  1. 100max
  2. 51
  3. 32
  4. 43
  5. 14
value = 7n = 5

The heap is the array [10, 5, 3, 4, 1]. We want to insert 7 and keep both rules: the tree stays complete, and every parent stays \ge its children.

Step 1: A max-heap in an array

def insert(heap, value):    heap.append(value)                  # 1. add at the end    i = len(heap) - 1    while i > 0:        parent = (i - 1) // 2        if heap[i] <= heap[parent]:     # parent already bigger            break        heap[i], heap[parent] = heap[parent], heap[i]        i = parent                      # keep climbingheap = [10, 5, 3, 4, 1]insert(heap, 7)print(heap)            # [10, 5, 7, 4, 1, 3]small = [10, 5, 3]insert(small, 12)print(small)           # [12, 10, 3, 5]
Time
O(log n)
Space
O(1)
insert 7
1 swap
insert 12 into [10, 5, 3]
2 swaps, new root
worst case
floor(log2 n) swaps

Insert always adds at the end, which keeps the shape, then bubbles up, which fixes the order. Never insert at the root: that breaks the shape and costs O(n) to shift the list.

In the real world

The same heap operations doing real jobs. Pick one and step through it.

A line where the most important guest is always at the front. Arrivals join at the back and move up past anyone less important.

Step 1 of 8

The line as a heap

10front753

VIP levels [10, 7, 5, 3]. The level-10 guest is at the front (the root). The rest are only partly ordered, and that is enough.

Step 1: The line as a heap

import heapqline = []                        # heapq is a min-heap, so store -levelfor level in [10, 7, 5, 3]:    heapq.heappush(line, -level)print(-line[0])                  # peek: 10heapq.heappush(line, -8)         # level 8 arrivesprint(-heapq.heappop(line))      # serve: 10print(-line[0])                  # next up: 8

Common mistakes

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

  • Sifting the wrong way

    critical

    A new value at the bottom can only be wrong relative to its parent, so insert sifts up. A value placed at the root can only be wrong relative to its children, so extract sifts down. Mixing them up leaves the heap broken.

    Wrong
    def insert(heap, x):    heap.append(x)    sift_down(heap, len(heap) - 1)   # a leaf has no children
    Right
    def insert(heap, x):    heap.append(x)    sift_up(heap, len(heap) - 1)     # climb towards the root
  • Forgetting heapq is a min-heap

    critical

    heapq.heappop always returns the smallest value. Code that expects the largest silently gets the wrong answer. Negate on the way in and on the way out.

    Wrong
    heapq.heappush(h, score)best = heapq.heappop(h)          # smallest, not best
    Right
    heapq.heappush(h, -score)best = -heapq.heappop(h)         # largest
  • Not checking child bounds

    critical

    Near the bottom, 2i + 1 or 2i + 2 can be past the end. Reading heapr without r < n raises IndexError, or worse, reads a stale value in a fixed-size array.

    Wrong
    if heap[l] > heap[largest]: largest = lif heap[r] > heap[largest]: largest = r
    Right
    if l < n and heap[l] > heap[largest]: largest = lif r < n and heap[r] > heap[largest]: largest = r
  • Swapping with the smaller child

    major

    In a max-heap the node must swap with its larger child. Swapping with the smaller one puts a value above its bigger sibling, breaking the heap: [3, 7, 5] would become [5, 7, 3].

    Wrong
    child = l if heap[l] < heap[r] else r    # smaller child
    Right
    child = l if heap[l] > heap[r] else r    # larger child (max-heap)
  • Inserting at the front

    major

    list.insert(0, x) shifts every element (O(n)) and scrambles every parent-child pair. New values always go at the end, then sift up.

    Wrong
    heap.insert(0, x)                # O(n), breaks every link
    Right
    heapq.heappush(heap, x)          # append + sift up: O(log n)
  • list.remove on a heap

    minor

    Removing from the middle shifts later elements left, so children end up under the wrong parents. Swap the target with the last slot, pop, then sift; or call heapify afterwards for O(n).

    Wrong
    h.remove(x)                      # heap order now broken
    Right
    i = h.index(x)h[i] = h[-1]; h.pop()heapq.heapify(h)                 # or sift i up/down in O(log n)

Interview tips

  • How to explain it

    • Insert: add at the end, sift up. Extract: move the last value to the root, sift down. Peek: read index 0.
    • Every sift walks one root-to-leaf path, so it costs O(log n): the height of a complete tree.
    • Update key sifts up if the value got more important, down if less. Delete fills the hole with the last value and sifts either way.
  • Spot it in the wild

    • Priority queues, task schedulers and event simulations.
    • Dijkstra and Prim: extract-min plus decrease-key.
    • Top-k, k-th largest, running median and merging k sorted lists.
  • Memory tricks

    • IPE: Insert at the end, Percolate up, Extract from the top.
    • New things climb, the replacement sinks.
    • k largest? Keep a min-heap of size k. k smallest? A max-heap of size k.
  • Watch out

    • heapq is min-only: negate for a max-heap.
    • Check l < n and r < n before reading children.
    • Peek or extract on an empty heap must be guarded.