Sub topic 11
Kruskal's Algorithm for Minimum Spanning Trees
This chapter assumes you know the DisjointSet class from the earlier chapters (union by size, path compression, and union returning True only when it merges two different sets). You should also know what a weighted undirected graph is and how sorting works.
The problem
A spanning tree of a connected graph with n vertices is a set of n - 1 edges that connects every vertex and contains no cycle. A minimum spanning tree (MST) is the spanning tree with the smallest total edge weight. Typical uses are laying cable between sites or connecting towns with the least road.
The greedy idea
Kruskal's algorithm builds the MST one edge at a time:
- Sort all edges by weight, lightest first.
- Look at each edge in order.
- Keep the edge if its endpoints are in different components. Skip it if they are already connected, because keeping it would close a cycle.
Union-find answers the question in step 3. This is the same test used for cycle detection: union returns False exactly when the two endpoints already share a set.
Implementation
The class below is the one from the previous chapters, repeated so the example runs on its own.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.count = n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.count -= 1
return True
def kruskal(n, edges):
# edges are (weight, u, v) tuples
ds = DisjointSet(n)
total = 0
chosen = []
for w, u, v in sorted(edges):
if ds.union(u, v):
chosen.append((u, v, w))
total += w
return total, chosen
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 2, 3)]
print(kruskal(4, edges)) # (6, [(0, 1, 1), (2, 3, 2), (1, 2, 3)])Putting the weight first in each tuple lets sorted order the edges by weight without a custom key.
Tracing the example
| Edge (weight, u, v) | Same set before? | Action | Components left |
|---|---|---|---|
| (1, 0, 1) | No | Keep | 3 |
| (2, 2, 3) | No | Keep | 2 |
| (3, 1, 2) | No | Keep | 1 |
| (4, 0, 2) | Yes | Skip | 1 |
The total is 1 + 2 + 3 = 6. The edge of weight 4 is skipped because 0 and 2 are already linked through 1.
Why the greedy choice is safe
Suppose the lightest remaining edge joins two different components. Any spanning tree must connect those two components somehow. If it uses a heavier edge for that, you can swap in the lighter edge without increasing the total. So keeping the lightest cross-component edge never rules out an optimal tree. This is the cut property.
Cost
Sorting costs O(E log E). The loop makes at most E union calls, each nearly constant time amortized, so sorting dominates. Without the two optimizations from earlier chapters, the loop could cost O(E · V) on a chain-shaped forest and become the bottleneck.
Common errors
- Assuming the graph is connected. On a disconnected graph the loop produces a minimum spanning forest. Check
len(chosen) == n - 1, ords.count == 1, if you need a single tree. - Forgetting to sort. Without the sort the result is a spanning tree, but not a minimum one.
- Expecting a unique answer. With tied weights, different orderings can pick different edges. The total weight is always the same.
- Stopping late. You can break out of the loop once
len(chosen) == n - 1. This saves work but does not change the result.
Exercise
Modify kruskal so that it returns None when the graph is not connected. What condition do you check, and where?
Show answer
After the loop, check ds.count != 1 (or len(chosen) != n - 1). If it holds, return None. In the code this means adding if len(chosen) != n - 1: return None just before return total, chosen. For example, kruskal(4, [(1, 0, 1), (2, 2, 3)]) keeps both edges but leaves two components, so it returns None.