Sub topic 9
Priority Queues with Binary Heaps
Prim's algorithm keeps asking one question: which edge leaving the tree is the lightest right now? A priority queue answers that question quickly. This chapter assumes you know Big-O notation, Python lists and tuples, and what a complete binary tree looks like.
The Operations a Priority Queue Needs
A priority queue stores items that each have a key and always gives back the item with the smallest key. Prim's algorithm uses three operations:
| Operation | Meaning | Binary heap cost |
|---|---|---|
| push | Insert an item with a key | O(log n) |
| pop-min | Remove and return the smallest item | O(log n) |
| peek | Look at the smallest item without removing it | O(1) |
A sorted list makes pop-min cheap but push slow (O(n)). An unsorted list does the opposite. A binary heap gets both operations to O(log n).
How a Binary Heap Works
A binary heap is a complete binary tree stored in a flat array. It keeps one rule, the heap property: every parent's key is less than or equal to its children's keys. So the smallest key is always at the root, index 0.
The tree has no pointers. For the node at index i:
- the left child is at
2*i + 1 - the right child is at
2*i + 2 - the parent is at
(i - 1) // 2
Push appends the item at the end of the array and then sifts it up, swapping it with its parent while the parent is larger. Pop-min moves the last item to the root and sifts it down, swapping it with its smaller child until the heap property holds again. A complete tree with n nodes has height about log₂ n, so each sift does at most O(log n) swaps.
Python's heapq Module
Python ships a binary min-heap in heapq. It works on a plain list:
import heapq
heap = []
for item in [(4, "C"), (1, "A"), (3, "B"), (2, "D")]:
heapq.heappush(heap, item)
print(heap) # [(1, 'A'), (2, 'D'), (3, 'B'), (4, 'C')]
print(heap[0]) # (1, 'A') -- peek
while heap:
print(heapq.heappop(heap))
# (1, 'A')
# (2, 'D')
# (3, 'B')
# (4, 'C')Tuples compare element by element, so the first field acts as the key. Prim's algorithm pushes (weight, vertex, parent) tuples for this reason.
Common Errors
- Expecting the list to be sorted. Only
heap[0]is guaranteed to be the minimum. In the output above,(2, 'D')sits before(3, 'B')by chance, not by design. - Wanting a max-heap.
heapqonly provides a min-heap. Push negated keys, such as(-w, item), to get max-heap behavior. - Ties on uncomparable data. When two keys are equal, Python compares the next tuple field. If that field is a dict or a custom object without
<, you get aTypeError. Put a comparable tiebreaker, such as a vertex number or a counter, second. - Building a heap with repeated pushes.
heapq.heapify(lst)turns an existing list into a heap in O(n), which beats n pushes at O(n log n).
No Decrease-Key: Lazy Deletion
Textbook Prim lowers a vertex's key when it finds a cheaper edge to that vertex. This operation is called decrease-key, and heapq does not have it. The standard workaround is lazy deletion: push a new entry with the lower key and leave the old one in the heap. When an entry pops for a vertex that has already been handled, skip it as stale.
Exercise
Starting from the heap [1, 3, 2, 7, 4, 5], you call heappop once. Show the array after the pop, step by step.
Show answer
Remove 1 and move the last item, 5, to the root: [5, 3, 2, 7, 4]. The children of 5 are 3 and 2. The smaller one is 2, so swap: [2, 3, 5, 7, 4]. The value 5 is now at index 2 and has no children (index 5 is out of range), so the sift stops. Result: [2, 3, 5, 7, 4].
Exercise
You push the tuples (3, {"id": 1}) and (3, {"id": 2}) onto a heapq heap. What happens, and how do you fix it?
Show answer
Both keys are 3, so Python compares the dicts, and dicts do not support "<". The push raises TypeError. Fix it by adding a comparable tiebreaker before the payload, for example (3, 1, {"id": 1}) and (3, 2, {"id": 2}), or by using an incrementing counter.