Kodewick
Start learning →
Minimum spanning trees: Kruskal and Prim35 / 52

Minimum spanning trees: Kruskal and Prim

Lesson 35 of 52 · Part 6 · Graphs · about 18 minutes

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

  1. Sort all the edges by weight, cheapest first.
  2. 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.
  3. Stop once n − 1 edges are taken.

6 cities and 9 edges: the edges are looked at from cheapest up, those whose ends are already connected (they would close a cycle) are left out, and the thick lines are the ones 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).

Choose one

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?

Choose one

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).

parent012345012345

The 9 edges of Kruskal go through union in turn: parent[x] is x's parent; the smaller piece hangs under the larger, and at the end find(5) hangs 5 straight on the root on its way
main.py
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)
Output
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).

Guess the outputA wrong guess is fine

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))
Choose one

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?

Fill inTap one to fill a blank; tap a blank to take it back

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)
Exercise 1

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.

It should print
6
-1
3
exercise1.py
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)]))
Output
Press Run or Ctrl+Enter

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

Prim from 0: green is already in the tree, and the row below is the heap's (edge weight, vertex), in the true order of the heap list; a popped vertex already in the tree is skipped
main.py
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])
Output
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.

IdeaToolsTimeGood for
Kruskaledges cheapest first, take it if no cyclesorting + union-findO(e log e)sparse graphs; problems that give an edge list
Prim (heap)grow out from one vertexadjacency list + heapqO(e log n)when there is already an adjacency list
Prim (array)scan for the closest each timeadjacency matrixO(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.

Choose one

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?

Choose one

In a connected graph, all the edge weights are different. How many minimum spanning trees does it have?

Choose one

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?

Exercise 2

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.

It should print
20
18
0
exercise2.py
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)]))
Output
Press Run or Ctrl+Enter

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 simply edges.sort().
  • Union-find is handiest as a class with parent and size inside; 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.
main.py
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")])
Output
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.

Guess the outputA wrong guess is fine

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

Take-away

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