Sub topic 9
Priority Queues with Binary Heaps
Prim's algorithm, covered in the next chapter, repeatedly asks one question: of all the edges leaving the current tree, which one is lightest? Scanning every candidate edge each time costs O(E) per step. A priority queue answers the same question in O(log n) time. This chapter builds a binary heap from scratch, maps it onto Python's heapq module, and covers the details that matter for Prim: tie-breaking, the missing decrease-key operation, and how large the heap can grow.
This chapter assumes you know Big-O notation, Python lists and tuples, and how Python compares tuples element by element.
What a Priority Queue Promises
A priority queue is a collection where every item has a priority. It supports these operations:
| Operation | Meaning | Binary heap cost |
|---|---|---|
| `push(item)` | Insert an item | O(log n) |
| `pop()` | Remove and return the smallest item | O(log n) |
| `peek()` | Look at the smallest item without removing it | O(1) |
| `heapify(list)` | Build a queue from n items at once | O(n) |
| `decrease_key(item, p)` | Lower an existing item's priority | O(log n), but only with an index map |
A min-priority queue returns the smallest priority first. MST algorithms always want the lightest edge, so this chapter uses min-heaps throughout.
The Heap Invariant and Array Layout
A binary heap is a complete binary tree stored in a flat array. "Complete" means every level is full except possibly the last, which fills from left to right. Because the shape is fixed, the array needs no pointers. Positions follow from arithmetic on the index i:
- Parent of
i:(i - 1) // 2 - Left child of
i:2 * i + 1 - Right child of
i:2 * i + 2
The min-heap invariant says each node is less than or equal to its children. The smallest element is therefore always at index 0. The invariant says nothing about the order of siblings, so the array is not sorted.
A complete tree with n nodes has height ⌊log₂ n⌋. Every heap operation walks at most one root-to-leaf path, and that is where the O(log n) bounds come from.
Sift Up and Sift Down
Two repair routines keep the invariant true.
- Sift up, used by push: append the new item at the end of the array, then swap it with its parent while it is smaller than the parent.
- Sift down, used by pop: move the last item into the root, then swap it with its smaller child while it is larger than that child.
When sifting down, you must swap with the smaller child. Swapping with the larger one would put a value above a smaller sibling and break the invariant. This is the most common bug in hand-written heaps.
class MinHeap:
def __init__(self, items=None):
self.a = list(items) if items else []
# Bottom-up heapify: sift down every internal node, last to first.
for i in range(len(self.a) // 2 - 1, -1, -1):
self._sift_down(i)
def __len__(self):
return len(self.a)
def peek(self):
if not self.a:
raise IndexError("peek at empty heap")
return self.a[0]
def push(self, item):
a = self.a
a.append(item)
i = len(a) - 1
while i > 0:
p = (i - 1) // 2
if a[i] < a[p]:
a[i], a[p] = a[p], a[i]
i = p
else:
break
def pop(self):
a = self.a
if not a:
raise IndexError("pop from empty heap")
top = a[0]
last = a.pop()
if a:
a[0] = last
self._sift_down(0)
return top
def _sift_down(self, i):
a = self.a
n = len(a)
while True:
left = 2 * i + 1
right = left + 1
smallest = i
if left < n and a[left] < a[smallest]:
smallest = left
if right < n and a[right] < a[smallest]:
smallest = right
if smallest == i:
return
a[i], a[smallest] = a[smallest], a[i]
i = smallest
h = MinHeap()
for edge in [(4, 0, 2), (1, 0, 1), (5, 2, 3), (3, 1, 2), (2, 1, 3)]:
h.push(edge)
while h:
print(h.pop())
# (1, 0, 1)
# (2, 1, 3)
# (3, 1, 2)
# (4, 0, 2)
# (5, 2, 3)
print(MinHeap([5, 3, 8, 1, 9, 2]).a) # [1, 3, 2, 5, 9, 8]The items are (weight, u, v) tuples, which are the edges of the four-vertex graph used throughout this tutorial. Python compares tuples by their first element, so the heap orders them by weight.
Why heapify is O(n) and not O(n log n)
Pushing n items one at a time costs O(n log n). Bottom-up heapify is faster. About half the nodes are leaves and need no work. A quarter sit one level up and sift down at most one step. An eighth sift down at most two steps, and so on. The total work is n · Σ k/2^(k+1), and that sum converges to a constant, so heapify runs in O(n). Prim does not depend on this, because it pushes edges as it discovers them. It does matter when you already hold all the items, for example when building a heap of all edges as an alternative to sorting them in Kruskal's algorithm.
Python's heapq Module
You rarely need the class above in production. The heapq module runs the same algorithms on a plain list and is implemented in C.
import heapq
heap = []
heapq.heappush(heap, (4, 0, 2))
heapq.heappush(heap, (1, 0, 1))
heapq.heappush(heap, (3, 1, 2))
print(heap[0]) # (1, 0, 1) peek
print(heapq.heappop(heap)) # (1, 0, 1)
data = [5, 3, 8, 1, 9, 2]
heapq.heapify(data) # in place, O(n)
print(data) # [1, 3, 2, 5, 9, 8]
# heappushpop: push then pop, faster than two separate calls
print(heapq.heappushpop(data, 4)) # 1
print(data[0]) # 2Common Errors
Comparing payloads that cannot be compared
When two tuples have equal weights, Python compares their second elements, then their third. That works for integer vertex IDs. If the payload is a dict, a custom object, or None mixed with ints, a tie raises TypeError.
import heapq
import itertools
heap = []
counter = itertools.count()
def push(heap, priority, payload):
# The counter breaks ties, so payloads are never compared.
heapq.heappush(heap, (priority, next(counter), payload))
push(heap, 2, {"edge": ("a", "b")})
push(heap, 2, {"edge": ("c", "d")}) # same priority, no TypeError
print(heapq.heappop(heap)[2]) # {'edge': ('a', 'b')}The counter also makes ties pop in insertion order, which keeps runs reproducible.
Mutating an entry inside the heap
Changing heap[k] in place, or changing an object that an entry refers to, breaks the invariant without any error. Later pops then return wrong answers. Treat heap entries as immutable.
Treating the list as sorted
heap[1] is not the second-smallest item. Only heap[0] has a guaranteed position. Read items in order with repeated heappop, or call sorted(heap).
The Missing Decrease-Key
Prim's algorithm conceptually keeps one entry per vertex outside the tree: the lightest known edge connecting it to the tree. When a lighter edge to vertex u appears, u's priority should drop. A binary heap can do this in O(log n) by sifting the entry up, but only if it knows where the entry sits in the array. heapq stores no such positions, so it has no decrease-key.
There are two standard ways around this.
| Approach | How it works | Heap size | Prim's time |
|---|---|---|---|
| Lazy deletion | Push a new entry each time; when you pop an entry for a vertex already in the tree, discard it as stale | Up to E | O(E log E) = O(E log V) |
| Indexed heap | Keep a `pos[vertex]` map, update it on every swap, and sift up on decrease | At most V | O(E log V) |
The two have the same asymptotic cost. E ≤ V², so log E ≤ 2 log V, and O(log E) equals O(log V). The lazy version needs O(E) memory for the heap rather than O(V), and it does some extra pops. In exchange, it is short and uses only the standard library. This tutorial's Prim implementation uses the lazy approach, which explains its if visited[v]: continue line.
Edge Cases
- Empty heap:
heapq.heappop([])raisesIndexError. Loops should testwhile heap:. - Floating-point weights: These compare fine. A
NaNweight compares false against everything and silently corrupts the ordering, so reject it when reading input. - Equal weights: The heap still works, but the order of ties depends on the remaining tuple fields. When several edges share a weight, different tie orders can produce different but equally light MSTs. The uniqueness chapter covers this.
Exercise
Starting from an empty min-heap, push 5, 3, 8, 1 in that order using sift up. Show the array after all four pushes. Then call pop once. What does pop return, and what is the array afterwards?
Show answer
After the pushes the array is [1, 3, 8, 5]. Pushing 1 places it at index 3. It swaps with its parent 5 at index 1, then with 3 at index 0. Pop returns 1 and moves the last item, 5, to the root, giving [5, 3, 8]. Sifting 5 down swaps it with its smaller child 3, so the result is [3, 5, 8].
Exercise
In lazy-deletion Prim on a connected graph with V vertices and E edges, what is the largest number of entries the heap can hold, and why does the bound O(E log E) not exceed O(E log V)?
Show answer
Each undirected edge is pushed at most once from each endpoint, and only while the other endpoint is unvisited. That bounds the pushes by O(E), and in practice each edge is pushed about once. A simple graph has E ≤ V(V-1)/2 < V², so log E < 2 log V, and O(E log E) = O(E log V).
Exercise
This code raises TypeError: heapq.heappush(h, (3, Node("a"))); heapq.heappush(h, (3, Node("b"))), where Node defines no ordering. Explain the cause and give a fix.
Show answer
The two weights tie, so Python compares the second tuple elements, and Node objects do not support <. The fix is to insert a tiebreaker that is always comparable, such as a counter: heapq.heappush(h, (3, next(counter), Node("a"))), with counter = itertools.count(). Then the Node objects are never compared.