Minimum spanning trees: Kruskal and Prim
A minimum spanning tree joins all n vertices with n − 1 edges of least total weight; Kruskal takes edges from the cheapest up and uses union-find to skip those that would close a cycle, while Prim grows from one vertex with heapq.
Fibre is to be laid between six cities, and each link between two cities costs a different amount. Any two cities must be able to talk (passing through others is fine) for the lowest total cost: which links should be laid? n cities need only n − 1 links: one more would close a circle, and removing any link on that circle keeps everyone connected and saves money. Such a set of edges is a spanning tree, and the one with the smallest total weight is the minimum spanning tree (MST). Power grids, pipelines and cluster analysis all compute one. The two classic algorithms work in opposite directions: Kruskal starts from the cheapest edges, Prim grows outwards from one city; in Python each needs one tool, union-find and heapq respectively.
Kruskal: start from the cheapest edges
- Sort all the edges by weight, cheapest first.
- Go through them one by one: if the two ends are not yet connected, take the edge; if they already are, taking it would close a cycle, so skip it.
- Stop once n − 1 edges are taken.
Why is "cheapest first" never a mistake? Split the vertices into any two groups: the cheapest edge between the two groups can always be part of some minimum spanning tree (swapping it in can only save). Each edge Kruskal takes is exactly the cheapest edge between the two pieces it joins. This is called the cut property.
The hard part is step 2, "are the two ends already connected". A BFS every time costs O(n); union-find makes it nearly O(1).
Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. In what order does Kruskal pick edges?
Same graph again. Which is the first edge Kruskal skips?
Union-find: are two vertices in the same piece?
Union-find keeps each piece as a tree in one list, parent: parent[x] is x's parent, and a root is its own parent. Two vertices with the same root are in the same piece.
find(x): follow parent up to the root.union(a, b): find both roots and hang one under the other, merging the two pieces into one.
Two things make it fast: union by size, hanging the smaller tree under the larger so trees never grow tall; and path compression, making every vertex that find walks past point straight at the root, so next time it is one step. Together they bring the average cost of each operation close to O(1).
1n = 62edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4),3 (2, 4, 6), (3, 4, 5), (3, 5, 7), (4, 5, 3)] # (u, v, weight)4 5parent = list(range(n))6size = [1] * n7 8def find(x):9 if parent[x] != x:10 parent[x] = find(parent[x]) # path compression: point straight at the root11 return parent[x]12 13def union(a, b):14 ra, rb = find(a), find(b)15 if ra == rb:16 return False # already in the same piece17 if size[ra] < size[rb]:18 ra, rb = rb, ra19 parent[rb] = ra # the smaller hangs under the larger20 size[ra] += size[rb]21 return True22 23total = 024picked = []25for u, v, w in sorted(edges, key=lambda e: e[2]):26 if union(u, v):27 picked.append((u, v, w))28 total += w29 if len(picked) == n - 1:30 break31 else:32 print("left out", (u, v, w), "(a cycle)")33print("taken", picked)34print("total", total)35print("parent", parent)36find(5)37print("after find(5)", parent)
left out (0, 1, 4) (a cycle) left out (2, 3, 4) (a cycle) taken [(1, 2, 1), (1, 3, 2), (0, 2, 3), (4, 5, 3), (3, 4, 5)] total 14 parent [1, 1, 1, 1, 1, 4] after find(5) [1, 1, 1, 1, 1, 1]
find is written recursively, but with union by size a tree is never taller than log₂ n (just 17 levels for 100,000 vertices), so it never gets near the recursion limit.
Kruskal's time goes mostly on sorting: O(e log e); the union-find part is nearly O(e).
This union-find has no path compression and no union by size. What does it print?
1parent = list(range(5))2 3def find(x):4 while parent[x] != x:5 x = parent[x]6 return x7 8def union(a, b):9 ra, rb = find(a), find(b)10 if ra != rb:11 parent[rb] = ra12 13union(0, 1)14union(2, 3)15union(1, 3)16print(parent, find(3))
union(0, 1): parent[1] = 0. union(2, 3): parent[3] = 2. union(1, 3) joins the two roots: find(1) = 0 and find(3) = 2, so what changes is parent[2] = 0, and 3's parent stays 2. find(3) walks 3 → 2 → 0, so the root is 0. Without path compression, parent[3] is never changed to 0.6 vertices start as roots (parent[i] = i). Do union(0, 1), union(2, 3), union(1, 3) in turn, where union(a, b) is parent[find(a)] = find(b). What is the parent array now?
What should Kruskal do with an edge whose ends are already connected? Pick one so the program prints the minimum spanning tree's total, 18.
1edges = [(0, 1, 6), (0, 2, 1), (1, 2, 4), (1, 3, 5), (2, 3, 7),2 (2, 4, 3), (3, 4, 2), (3, 5, 8), (4, 5, 9)]3parent = list(range(6))4 5def find(x):6 if parent[x] != x:7 parent[x] = find(parent[x])8 return parent[x]9 10total = 011for u, v, w in sorted(edges, key=lambda e: e[2]):12 a, b = find(u), find(v)13 if a == b:14 15 parent[a] = b16 total += w17print(total)
continue. With break, it stops at 1–3, the first edge that makes a cycle, before 5 is connected, and the total is only 10. pass doesn't work either: a and b are the same root, so parent[a] = b changes nothing, but total += w still runs, every cycle edge gets counted, and you get 45.The cheapest way to connect all cities
✓Complete min_cost(n, roads): n cities are numbered 0 to n − 1, and (u, v, w) in roads is a road that can be built. Use Kruskal to return the lowest total cost connecting every city; if no choice of roads connects them all, return -1.
6 -1 3
1def min_cost(n, roads):2 parent = list(range(n))3 size = [1] * n4 5 def find(x):6 if parent[x] != x:7 parent[x] = find(parent[x])8 return parent[x]9 10 total = 011 used = 012 # edges cheapest first; take one only when its ends have different roots, stop at n - 113 return -114 15print(min_cost(3, [(0, 1, 5), (0, 2, 6), (1, 2, 1)]))16print(min_cost(4, [(0, 1, 3), (2, 3, 4)]))17print(min_cost(4, [(0, 1, 1), (1, 2, 1), (2, 3, 1), (0, 3, 1), (0, 2, 2)]))
Prim: grow out from one vertex
Prim keeps just one tree: start from any vertex, and each time, among the edges with "one end in the tree and one outside", pick the cheapest and pull its outside end in. This is the cut property again: the tree and the rest are the two groups, and the edge picked is the cheapest between them.
"Pick the cheapest" goes to heapq again, written much like Dijkstra; the only difference is that the heap compares this one edge's weight, not the total distance from the start.
Heap
1import heapq2 3n = 64edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4),5 (2, 4, 6), (3, 4, 5), (3, 5, 7), (4, 5, 3)]6graph = [[] for _ in range(n)]7for u, v, w in edges:8 graph[u].append((v, w))9 graph[v].append((u, w))10 11def prim(graph, start):12 in_tree = [False] * len(graph)13 heap = [(0, start, -1)] # (edge weight, vertex, the vertex it comes from)14 total = 015 picked = []16 while heap:17 w, u, frm = heapq.heappop(heap)18 if in_tree[u]:19 continue # already in the tree: this edge would close a cycle20 in_tree[u] = True21 total += w22 if frm != -1:23 picked.append((frm, u, w))24 for v, wv in graph[u]:25 if not in_tree[v]:26 heapq.heappush(heap, (wv, v, u))27 return total, picked28 29total, picked = prim(graph, 0)30print("taken", picked)31print("total", total)32print("starting from 5:", prim(graph, 5)[0])
taken [(0, 2, 3), (2, 1, 1), (1, 3, 2), (3, 4, 5), (4, 5, 3)] total 14 starting from 5: 14
The two algorithms may pick slightly different edges (edges of equal weight can be chosen in more than one way), but the total is always the same: a minimum spanning tree's total weight is unique.
| Idea | Tools | Time | Good for | |
|---|---|---|---|---|
| Kruskal | edges cheapest first, take it if no cycle | sorting + union-find | O(e log e) | sparse graphs; problems that give an edge list |
| Prim (heap) | grow out from one vertex | adjacency list + heapq | O(e log n) | when there is already an adjacency list |
| Prim (array) | scan for the closest each time | adjacency matrix | O(n²) | dense graphs, such as "every pair of points joined" |
In interviews: "the cheapest way to connect all cities", "min cost to connect all points" are minimum spanning trees. When the graph is not connected, fewer than n − 1 edges get taken and the answer is -1. Union-find is a favourite problem on its own (friend circles, redundant connection, accounts merge): be able to write find with path compression and union by size straight off.
Edges A–B 3, A–C 1, B–C 2, B–D 4, C–D 5, D–E 2, C–E 6. Running Prim from A, in what order do edges join the tree?
A–C B–C D–E B–D is Kruskal's order: D–E is only 2, but at first neither end is in the tree, so Prim can't reach it.In a connected graph, all the edge weights are different. How many minimum spanning trees does it have?
The triangle A–B 2, B–C 2, A–C 3 has minimum spanning tree A–B and B–C. In the tree, the path from A to C is 4 long. What's the shortest path from A to C in the graph?
Min cost to connect all points
✓Complete connect_points(points): there are a few points on a plane, joining two costs their Manhattan distance |x1 - x2| + |y1 - y2|, and any two can be joined. Use Prim (heapq) to return the smallest total cost joining all the points.
20 18 0
1import heapq2 3def connect_points(points):4 n = len(points)5 in_tree = [False] * n6 heap = [(0, 0)] # (cost, index of the point)7 total = 08 # pop the cheapest; skip it if already in the tree; otherwise add it and push its cost to every point outside9 return total10 11print(connect_points([(0, 0), (2, 2), (3, 10), (5, 2), (7, 0)]))12print(connect_points([(3, 12), (-2, 5), (-4, 1)]))13print(connect_points([(0, 0)]))
How you write it at work
The standard library has no union-find and no minimum spanning tree; what you write is the few lines from the union-find stage:
- Sort with
sorted(edges, key=lambda e: e[2]), or store edges as(w, u, v)and simplyedges.sort(). - Union-find is handiest as a class with
parentandsizeinside; with string vertices, use dicts. - To know only "how many groups do these fall into" (weights don't matter), union-find is even handier than BFS: each successful union lowers the group count by one.
1class UnionFind:2 def __init__(self, items):3 self.parent = {x: x for x in items}4 self.size = {x: 1 for x in items}5 self.groups = len(self.parent)6 7 def find(self, x):8 root = x9 while self.parent[root] != root:10 root = self.parent[root]11 while self.parent[x] != root: # second pass: everything on the way points straight at the root12 self.parent[x], x = root, self.parent[x]13 return root14 15 def union(self, a, b):16 ra, rb = self.find(a), self.find(b)17 if ra == rb:18 return False19 if self.size[ra] < self.size[rb]:20 ra, rb = rb, ra21 self.parent[rb] = ra22 self.size[ra] += self.size[rb]23 self.groups -= 124 return True25 26uf = UnionFind(["Ann", "Bea", "Cal", "Dee", "Ed"])27for a, b in [("Ann", "Bea"), ("Cal", "Dee"), ("Bea", "Ann"), ("Dee", "Ann")]:28 uf.union(a, b)29print("groups:", uf.groups)30print("Bea and Cal in one group:", uf.find("Bea") == uf.find("Cal"))31print("people in Ed's group:", uf.size[uf.find("Ed")])
groups: 2 Bea and Cal in one group: True people in Ed's group: 1
This find is a loop: it walks up to the root first, then a second pass points every vertex on the way straight at the root, so recursion depth never comes into it.
When you only want groups, the weights don't matter: just count how many unions succeed. What does this print?
1parent = {x: x for x in "abcdef"}2 3def find(x):4 while parent[x] != x:5 x = parent[x]6 return x7 8groups = len(parent)9for a, b in [("a", "b"), ("c", "d"), ("b", "a"), ("d", "e"), ("e", "c")]:10 ra, rb = find(a), find(b)11 if ra != rb:12 parent[rb] = ra13 groups -= 114print(groups, find("e") == find("c"))
Summary
Minimum spanning tree: n − 1 edges, no cycle, least total weight
- Kruskal: edges cheapest first, taken only when the ends aren't connected; O(e log e)
- Union-find: find walks up to the root, union joins two roots; path compression + union by size
- Prim: grow out from one vertex, heapq gives the cheapest edge leading out, skip what's already in the tree
- Both give the same total; fewer than n − 1 edges means the graph isn't connected
1def find(x):2 if parent[x] != x: parent[x] = find(parent[x])3 return parent[x]4for u, v, w in sorted(edges, key=lambda e: e[2]):5 if union(u, v): total += w