Sub topic 6
Priority Queues and Binary Heaps
This chapter assumes you can read Python lists, tuples, and loops, and that you know Big-O notation. It also builds on the previous chapters: Dijkstra's algorithm repeatedly picks the unvisited vertex with the smallest tentative distance. In the hand trace you found that vertex by scanning every candidate. This chapter covers the data structure that makes that choice cheap.
What a Priority Queue Is
A priority queue is an abstract data type, which means it is defined by the operations it supports and not by how it stores data. Each item has a priority, and the queue always hands back the item with the best priority first. For Dijkstra, "best" means the smallest distance, so we want a min-priority queue.
The core operations are:
| Operation | Meaning | Used in Dijkstra for |
|---|---|---|
| insert(item, priority) | Add an item | Recording a new tentative distance |
| extract-min | Remove and return the smallest item | Choosing the next vertex to finalize |
| peek | Look at the smallest item without removing it | Rarely needed |
| decrease-key(item, new priority) | Lower an existing item's priority | Updating a vertex after relaxation |
A regular queue is first-in, first-out, and that is what breadth-first search uses. BFS works because every edge has the same cost, so the order of discovery is the order of distance. When edge weights differ, discovery order no longer matches distance order. A priority queue replaces the FIFO queue so that order comes from distance.
Simple Implementations and Their Costs
Before looking at heaps, it helps to see why the obvious structures fall short. Let n be the number of items in the queue.
| Structure | insert | extract-min | decrease-key |
|---|---|---|---|
| Unsorted list or array | O(1) | O(n) | O(1) if you know the index |
| Sorted list | O(n) | O(1) | O(n) |
| Binary heap | O(log n) | O(log n) | O(log n) if you know the index |
The unsorted array is what the hand trace effectively did. It is not always a bad choice. On a dense graph, where the edge count E is close to V², the array version of Dijkstra runs in O(V²), and that can beat a heap. The chapter on running time covers this trade-off. For the sparse graphs common in practice, such as road networks, the binary heap wins because both of its main operations are logarithmic.
The Binary Heap Structure
A binary heap is a binary tree with two properties:
- Shape property. The tree is complete. Every level is full except possibly the last, and the last level fills from left to right.
- Heap property. In a min-heap, every node's value is less than or equal to its children's values. The smallest item is therefore always at the root.
The heap property is weaker than sorting. Siblings can be in any order, and a node deep in the left subtree can be smaller than a node high in the right subtree. Because the heap keeps only this partial order, insert and extract-min stay cheap.
Storing the tree in an array
Since the tree is complete, it fits in a plain list with no pointers. The root sits at index 0, and for a 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
Each parent is no larger than its children: 1 ≤ 3, 1 ≤ 2, 3 ≤ 7, 3 ≤ 4, 2 ≤ 5. The list is not sorted, since 2 comes after 3, but it is still a valid heap.
Insert: sift up
To insert, append the item at the end of the list. This keeps the tree complete but may break the heap property. Fix it by swapping the item with its parent while it is smaller than the parent. The tree's height is ⌊log₂ n⌋, so there are at most O(log n) swaps.
Extract-min: sift down
The minimum is at index 0. Remove it by moving the last element into the root, which keeps the shape valid. Then swap that element downward with its smaller child until neither child is smaller. This also takes O(log n) swaps.
Here is extract-min on [1, 3, 2, 7, 4, 5]:
- Remove 1. Move the last element, 5, to the root:
[5, 3, 2, 7, 4]. - The root's children are 3 and 2. The smaller one is 2, at index 2. Swap:
[2, 3, 5, 7, 4]. - Index 2 would have children at indices 5 and 6, which do not exist. Stop.
The new minimum, 2, is at the root.
A Heap From Scratch
Writing the heap once yourself makes the library version easier to understand. This class works with any items that support <, including (distance, vertex) tuples.
class MinHeap:
def __init__(self):
self.a = []
def __len__(self):
return len(self.a)
def push(self, item):
a = self.a
a.append(item)
i = len(a) - 1
while i > 0:
parent = (i - 1) // 2
if a[i] < a[parent]:
a[i], a[parent] = a[parent], a[i]
i = parent
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
i, n = 0, len(a)
while True:
left, right = 2 * i + 1, 2 * i + 2
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:
break
a[i], a[smallest] = a[smallest], a[i]
i = smallest
return top
h = MinHeap()
for item in [(5, "E"), (1, "C"), (4, "B"), (3, "D"), (2, "F")]:
h.push(item)
while h:
print(h.pop())
# (1, 'C')
# (2, 'F')
# (3, 'D')
# (4, 'B')
# (5, 'E')Items come out in priority order even though the list was never fully sorted. Popping everything like this is heapsort, which runs in O(n log n).
Python's heapq Module
In real code, use the standard library's heapq. It implements the same algorithm in C on top of an ordinary list, and it provides functions, not a class.
import heapq
heap = []
heapq.heappush(heap, (4, "B"))
heapq.heappush(heap, (1, "C"))
heapq.heappush(heap, (3, "D"))
print(heap) # [(1, 'C'), (4, 'B'), (3, 'D')]
print(heap[0]) # (1, 'C') peek is just index 0
print(heapq.heappop(heap)) # (1, 'C')
print(heapq.heappop(heap)) # (3, 'D')
data = [(7, "A"), (2, "B"), (9, "C"), (1, "D")]
heapq.heapify(data) # rearranges in place in O(n), faster than n pushes
print(data[0]) # (1, 'D')Keep these points about heapq in mind:
- It is a min-heap only. For a max-heap, push negated priorities.
- Tuples compare element by element.
(distance, vertex)orders by distance first, which is what Dijkstra needs. - The list is a heap only if you modify it solely through
heapqfunctions. Callingheap.sort()keeps it a valid heap, butheap.append(x)or assigning intoheap[i]can break the invariant without raising an error. - There is no decrease-key.
heapqdoes not track where an item sits in the list, so it cannot find a vertex and lower its priority.
Common Errors
Ties that compare unorderable values
When two distances are equal, Python compares the second tuple elements. Strings and integers compare fine, but dicts and most custom objects do not:
import heapq
heap = []
heapq.heappush(heap, (2, {"name": "X"}))
try:
heapq.heappush(heap, (2, {"name": "Y"}))
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'dict' and 'dict'This bug stays hidden until two equal distances meet, so small tests often miss it. The standard fix is to put a unique, increasing counter between the priority and the payload:
import heapq
import itertools
counter = itertools.count()
heap = []
heapq.heappush(heap, (2, next(counter), {"name": "X"}))
heapq.heappush(heap, (2, next(counter), {"name": "Y"}))
print(heapq.heappop(heap)[2]) # {'name': 'X'}The counter guarantees that the comparison never reaches the payload, and it also breaks ties in insertion order.
Treating the heap list as sorted
heap[0] is the minimum, but heap[1] is not necessarily the second smallest. In [1, 3, 2, 7, 4, 5], the second smallest value is 2, at index 2. To get items in order, pop them, or use heapq.nsmallest(k, heap).
Expecting to update an entry in place
Code that searches the list for a vertex and lowers its distance breaks the heap property, because the changed entry may now be smaller than its parent. Without a sift-up the heap returns wrong results and raises no error.
Exercises
Exercise
In an array-based binary heap, what is the parent index of the node at index 9, and what are the indices of the children of the node at index 4?
Show answer
The parent is (9 - 1) // 2 = 4. The children of index 4 are 24 + 1 = 9 and 24 + 2 = 10.
Exercise
Starting from the min-heap [1, 3, 2, 7, 4, 5], push the value 0. Show the list after each swap and give the final list.
Show answer
Append 0 at index 6: [1, 3, 2, 7, 4, 5, 0]. Its parent is index 2 (value 2), and 0 < 2, so swap: [1, 3, 0, 7, 4, 5, 2]. Now at index 2, the parent is index 0 (value 1), and 0 < 1, so swap: [0, 3, 1, 7, 4, 5, 2]. At the root, stop. Final list: [0, 3, 1, 7, 4, 5, 2].
Exercise
A program pushes (distance, vertex) tuples where each vertex is an instance of a custom class with no comparison methods. It passes all tests on small graphs but crashes on a large one with a TypeError. Explain why, and give a fix.
Show answer
The crash happens only when two entries have equal distances, because Python then compares the vertex objects, and the class does not define <. Small test graphs may never produce a tie. Fix it by pushing (distance, next(counter), vertex) with counter = itertools.count(), so ties are settled by the unique counter and the vertex objects are never compared. Pushing a comparable vertex ID in place of the object also works.
Exercise
You need the item with the largest priority each time, using heapq. How do you do it, and what must you remember when popping?
Show answer
Push (-priority, item) so that the largest priority becomes the smallest key. When you pop, negate the first element again to recover the original priority.