Kodewick
Start learning →
Heaps and heapq26 / 52

Heaps and heapq

Lesson 26 of 52 · Part 5 · Trees and heaps · about 18 minutes

A heap is a complete binary tree kept in a list, with the children of index i at 2i + 1 and 2i + 2 and no parent larger than its children, so the smallest is always h[0]; push and pop are O(log n).

An emergency room doesn't see patients in the order they arrived but the most urgent first; an operating system runs the highest-priority process first; Dijkstra's shortest paths needs "the closest vertex to the start" at every step. They all need one structure: take out the smallest (or largest) at any moment, while new items keep arriving. A sorted list gives the smallest in O(1), but inserting shifts items, O(n); an unsorted list inserts in O(1), but every search for the smallest scans everything. A heap does both in O(log n): with a million items, adding one or taking one costs about 20 swaps. Python's heapq is exactly this; this lesson writes one by hand first, then shows how heapq is used.

A tree kept in a list

A heap is a complete binary tree: every level is full except perhaps the last, which fills from left to right. Such a tree needs no left and right references; put it in a list level by level, left to right, and the positions follow fixed formulas:

  • index i's left child is at 2i + 1 and its right child at 2i + 2;
  • index i's parent is at (i − 1) // 2.

A min-heap's rule: every node is no larger than its children. So the smallest is always at the root, which is h[0]. (A max-heap is the reverse: every node is no smaller than its children. Python's heapq is a min-heap.)

10
31
73
44
22
55
66
10312273445566

One min-heap drawn two ways: read the tree level by level, left to right, and you get the list below; beside each node is its index

A heap only cares about parents and children, not siblings, so [1, 3, 2, 7, 4, 5, 6] is a valid heap but not a sorted list. Because it asks for so little, it is cheap to keep.

Fill inTap one to fill a blank; tap a blank to take it back

h is the min-heap from this step's picture. Pick what goes in the blank to find index 1's left child, so the program prints its two children, 7 4.

1h = [1, 3, 2, 7, 4, 5, 6]2i = 13left = 4print(h[left], h[left + 1])
Choose one

Which of these lists is a min-heap (indexes from 0)?

push: add at the end, sift up

A new item is first appended to the end of the list, the next free place on the tree's last level. It may now be smaller than its parent, which breaks the rule: so compare it with its parent, swap if it is smaller, and keep going up until it is no smaller than its parent or reaches the root. This is sifting up.

10
31
73
44
22
55
1031227344556

Pushing 0 into the min-heap [1, 3, 2, 7, 4, 5]: add it at the end, then swap it with its parent all the way up to the root
Guess the outputA wrong guess is fine

heappush 5, 3, 8 and 1 in turn, then print the list itself and h[0]. What does it print?

1import heapq2 3h = []4for x in [5, 3, 8, 1]:5    heapq.heappush(h, x)6print(h, h[0])
Choose one

Push 6 4 9 2 5 into an empty min-heap, in that order. What does the list look like?

Exercise 1

Write push

pop is already written. Complete push(a, x): add x at the end of the list, then sift it up, so that a stays a min-heap.

It should print
[1, 3, 2, 5, 9, 8]
[1, 2, 3, 5, 8, 9]
exercise1.py
1def push(a, x):2    a.append(x)3    i = len(a) - 14    # sift up: the parent is at (i - 1) // 2; swap while the parent is larger, up to the root5 6def pop(a):7    top = a[0]8    last = a.pop()9    if a:10        a[0] = last11        i, n = 0, len(a)12        while True:13            small = i14            for c in (2 * i + 1, 2 * i + 2):15                if c < n and a[c] < a[small]:16                    small = c17            if small == i:18                break19            a[i], a[small] = a[small], a[i]20            i = small21    return top22 23h = []24for x in [5, 3, 8, 1, 9, 2]:25    push(h, x)26print(h)27print([pop(h) for _ in range(6)])
Output
Press Run or Ctrl+Enter

pop: move the last to the root, sift down

Once the root is taken, the root is empty. You can't just lift a child up (the tree would lose a piece and no longer be complete); instead, pop() the last item of the list and put it at the root. It is most likely too large, so compare it with the smaller of its two children, swap if it is larger, and keep going down until it is no larger than its children or has none. This is sifting down.

10
31
73
44
22
55
66
10312273445566

Popping from [1, 3, 2, 7, 4, 5, 6]: the last item, 6, moves to the root, then swaps with its smaller child on the way down

Why swap with the smaller child: the one that moves up becomes the other child's parent, and only the smaller of the two is no larger than the other.

main.py
1class MinHeap:2    def __init__(self):3        self.a = []4 5    def push(self, x):6        a = self.a7        a.append(x)                        # add at the end8        i = len(a) - 19        while i > 0:                       # sift up10            p = (i - 1) // 211            if a[p] <= a[i]:12                break13            a[p], a[i] = a[i], a[p]14            i = p15 16    def pop(self):17        a = self.a18        top = a[0]19        last = a.pop()                     # take the last item20        if a:21            a[0] = last                    # put it at the root, then sift down22            self._down(0)23        return top24 25    def _down(self, i):26        a = self.a27        n = len(a)28        while True:29            small = i30            l, r = 2 * i + 1, 2 * i + 231            if l < n and a[l] < a[small]:32                small = l33            if r < n and a[r] < a[small]:34                small = r35            if small == i:36                return37            a[i], a[small] = a[small], a[i]38            i = small39 40    def __len__(self):41        return len(self.a)42 43h = MinHeap()44for x in [1, 3, 2, 7, 4, 5]:45    h.push(x)46h.push(0)47print(h.a)48print(h.pop(), h.a)49print([h.pop() for _ in range(len(h))])
Output
[0, 3, 1, 7, 4, 5, 2]
0 [1, 3, 2, 7, 4, 5]
[1, 2, 3, 4, 5, 7]

Popping them all comes out smallest to largest: that is next lesson's heap sort.

Choose one

Pop once from the min-heap [2, 4, 3, 8, 5, 7, 6] (the 2 comes out). What does the list look like now?

Choose one

While sifting down, 6's two children are 4 and 3. What goes wrong if 6 swaps with the bigger one, 4?

heapify: building a heap in O(n)

You already have a list and want to make it a heap. Pushing items one by one is n times O(log n). A faster way goes from the bottom up: the leaves are heaps on their own and need nothing; starting from the last node that has children (index n // 2 − 1) and moving back, sift each node down once. When a node's turn comes, its two subtrees are already heaps, so one sift down makes its whole subtree a heap.

90
41
13
84
72
25
66
90417213842566

Turning [9, 4, 7, 1, 8, 2, 6] into a min-heap in place: from index 2 back to the root, each node sifts down once

Why O(n): how far a node sinks depends on how high it is above the leaves. Half the nodes are leaves, 0 steps; a quarter are one level up, at most 1 step; only the root may go log n steps. In all, n/4 × 1 + n/8 × 2 + n/16 × 3 + … < n. Pushing one by one is the other way round: half the nodes are on the bottom level, and each may rise log n levels. Count it for 1023 numbers from largest to smallest (the worst order for a min-heap):

main.py
1def push_all(vals):2    a, swaps = [], 03    for x in vals:4        a.append(x)5        i = len(a) - 16        while i > 0 and a[(i - 1) // 2] > a[i]:7            p = (i - 1) // 28            a[p], a[i] = a[i], a[p]9            swaps += 110            i = p11    return a, swaps12 13def heapify(a):14    n, swaps = len(a), 015    for i in range(n // 2 - 1, -1, -1):   # from the last node with children, backwards16        while True:17            small = i18            l, r = 2 * i + 1, 2 * i + 219            if l < n and a[l] < a[small]:20                small = l21            if r < n and a[r] < a[small]:22                small = r23            if small == i:24                break25            a[i], a[small] = a[small], a[i]26            swaps += 127            i = small28    return a, swaps29 30vals = list(range(1023, 0, -1))31a1, s1 = push_all(vals)32a2, s2 = heapify(vals[:])33print("pushing one by one: swaps", s1)34print("heapify: swaps", s2)35print(a1[0], a2[0], a1[:7] == a2[:7])36print(heapify([9, 4, 7, 1, 8, 2, 6]))
Output
pushing one by one: swaps 8194
heapify: swaps 1013
1 1 False
([1, 4, 2, 9, 8, 7, 6], 4)

Pushing one by one made 8194 swaps, nearly 8 levels for every number (log₂ 1024 = 10); heapify made only 1013, fewer than n. Both built valid heaps, but the lists are not necessarily arranged the same way: a heap can have many valid shapes.

OperationCostHow
Look at the smallest, h[0]O(1)it is at the root
pushO(log n)add at the end, sift up
popO(log n)move the last to the root, sift down
heapify (build a heap)O(n)from n // 2 − 1 backwards, sift each down
Find or delete an arbitrary valueO(n)a heap only orders parents and children; no binary search

In interviews: "Why is heapify O(n) and not O(n log n)?" is a frequent follow-up; answer "most nodes are close to the leaves, so the sift-down steps add up to a constant times n". Know the index formulas cold: counting from 0 they are 2i + 1, 2i + 2 and (i − 1) // 2; many textbooks count from 1, giving 2i, 2i + 1 and i // 2.

Choose one

heapify runs on a list of 9 items. Which index is the first to sift down?

Choose one

Building a heap of n values: pushing them one by one, or heapify. How long does each take in the worst case?

Exercise 2

Write heapify

sift_down(a, i, n) is already written. Complete heapify(a): starting from the last node with children and going backwards, sift each node down once, turning a into a min-heap in place.

It should print
[1, 4, 2, 9, 8, 7, 6]
[1, 2, 3]
exercise2.py
1def sift_down(a, i, n):2    while True:3        small = i4        for c in (2 * i + 1, 2 * i + 2):5            if c < n and a[c] < a[small]:6                small = c7        if small == i:8            return9        a[i], a[small] = a[small], a[i]10        i = small11 12def heapify(a):13    n = len(a)14    # i from n // 2 - 1 down to 015 16a = [9, 4, 7, 1, 8, 2, 6]17heapify(a)18print(a)19b = [3, 2, 1]20heapify(b)21print(b)
Output
Press Run or Ctrl+Enter

How you write it at work

At work you use heapq directly. It is not a class but a set of functions working on a plain list, the same way as the version written by hand in this lesson:

main.py
1import heapq2 3h = [9, 4, 7, 1, 8, 2, 6]4heapq.heapify(h)                     # build a heap in place, O(n)5print(h, h[0])                       # h[0] is the smallest, no pop needed6heapq.heappush(h, 3)7print(heapq.heappop(h), heapq.heappop(h), h)8 9# a max-heap: store negatives and negate them on the way out10mx = []11for x in [5, 1, 8, 3]:12    heapq.heappush(mx, -x)13print(-heapq.heappop(mx), -mx[0])14 15# prioritised tasks: (priority, counter, item); tuples compare from the first item16tasks = []17order = 018for pri, name in [(2, "weekly report"), (1, "fix the outage"), (2, "answer email"), (3, "tidy the desk")]:19    heapq.heappush(tasks, (pri, order, {"name": name}))20    order += 121while tasks:22    pri, _, task = heapq.heappop(tasks)23    print(pri, task["name"])
Output
[1, 4, 2, 9, 8, 7, 6] 1
1 2 [3, 4, 6, 9, 8, 7]
8 5
1 fix the outage
2 weekly report
2 answer email
3 tidy the desk

The counter order in the middle can't be left out. When two tasks have the same priority, the tuples go on to compare their second items; if the second item is the dict itself, dicts can't be compared:

main.py
1import heapq2 3tasks = []4heapq.heappush(tasks, (2, {"name": "weekly report"}))5try:6    heapq.heappush(tasks, (2, {"name": "answer email"}))7except TypeError as e:8    print(type(e).__name__ + ": with equal priorities, two dicts can't be compared")
Output
TypeError: with equal priorities, two dicts can't be compared

With a counter that keeps rising, equal priorities fall back to comparing counters, which always works, and the item pushed first also comes out first. Lesson 7's Huffman tree meets the same problem.

  • heapq.heappushpop(h, x) (push, then pop) and heapq.heapreplace(h, x) (pop, then push) are a little faster than two separate calls.
  • For a priority queue shared between threads, use queue.PriorityQueue: it is heapq inside, with a lock around it.
  • For "the largest k", use heapq.nlargest(k, data); the next lesson shows why it is fast.
Guess the outputA wrong guess is fine

heapq.heapify turns [5, 4, 3, 2, 1] into a min-heap in place. What does this print?

1import heapq2 3h = [5, 4, 3, 2, 1]4heapq.heapify(h)5print(h, h[0])
Fill inTap one to fill a blank; tap a blank to take it back

A max-heap with heapq: negate on the way in, negate again on the way out. Pick what goes in the blank so the program prints 8 5.

1import heapq2 3mx = []4for x in [5, 1, 8, 3]:5    heapq.heappush(mx, )6print(-heapq.heappop(mx), -heapq.heappop(mx))

Summary

Take-away

Heaps: the smallest is always at h[0]

  • A complete binary tree in a list: children at 2i + 1 and 2i + 2, parent at (i − 1) // 2
  • A min-heap only keeps parents no larger than children; it is not sorted
  • push adds at the end and sifts up; pop moves the last to the root and sifts down: both O(log n)
  • heapify sifts down from n // 2 − 1 backwards: O(n)
  • heapq is a min-heap; negatives make a max-heap; tasks go in as (priority, counter, item)
1import heapq2heapq.heapify(h)          # O(n)3heapq.heappush(h, x)      # O(log n)4x = heapq.heappop(h)      # the smallest5heapq.heappush(h, (pri, order, task))