Step 16 Graphs — Minimum Spanning Tree
MST theory
A minimum spanning tree (MST) is the cheapest set of edges that connects every vertex of a weighted undirected graph — the answer to 'link all these points with minimum total cable/road cost'. This lesson covers what a spanning tree is, the cut property that justifies both classic algorithms, and how Prim's and Kruskal's each build the MST, including the disjoint-set structure Kruskal's depends on.
Spanning trees and minimum spanning trees
A spanning tree of a connected graph with V vertices is a subgraph that includes all V vertices, is connected, and has no cycles — which forces exactly V - 1 edges. Drop any one of those properties and it is not a spanning tree.
Many spanning trees usually exist; the MST is the one whose total edge weight is smallest. If the graph is disconnected, no spanning tree exists — instead each component gets its own MST, forming a minimum spanning forest. Edge weights need not be distances; any cost works, and negative weights are fine (unlike shortest-path algorithms, MST algorithms do not care).
The cut property — the one idea behind both algorithms
A cut splits the vertices into two groups. An edge crossing the cut connects the groups. The cut property states: the minimum-weight edge crossing any cut is safe — it belongs to some MST (to every MST, if its weight is unique).
Both algorithms are this theorem applied repeatedly. Prim's grows one group (the tree built so far) and takes the cheapest edge leaving it. Kruskal's considers edges in increasing order; adding the cheapest edge that connects two different components is safe because that edge is the minimum crossing the cut between its component and the rest. When you are stuck proving or debugging an MST solution, come back to this property.
Kruskal's algorithm + disjoint set (DSU)
Steps: sort all edges by weight ascending; walk through them, adding an edge whenever its endpoints are in different components, and merging those components; stop after V - 1 edges are added.
The 'different components?' test must be near-constant time, which is the disjoint set union (DSU) structure's job: find(x) returns the component's representative, with path compression flattening the tree as it goes; union(a, b) merges by size or rank. With both optimisations, operations are amortised almost O(1). Sorting dominates the cost: O(E log E) overall.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
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]
return True
def kruskal_mst_weight(n, edges):
dsu = DSU(n)
total, used = 0, 0
for w, u, v in sorted(edges): # edges as (weight, u, v)
if dsu.union(u, v):
total += w
used += 1
if used == n - 1:
break
return total if used == n - 1 else -1 # -1: graph disconnectedPrim's algorithm
Prim's grows a single tree from a start vertex. Maintain a min-heap of candidate edges (weight, to-vertex) leaving the visited set, plus a visited array. Repeatedly pop the cheapest candidate; if its far endpoint is unvisited, that edge joins the MST, the vertex becomes visited, and all its outgoing edges are pushed. Continue until V - 1 edges are chosen.
Cost with a binary heap is O(E log V). Prim's is usually preferred for dense graphs (many edges, where Kruskal's sort of a huge edge list dominates) and when the graph is given as an adjacency list; Kruskal's is simpler when you already have an edge list. Worked check: vertices 1-4 with edges 1-2 (1), 2-3 (2), 1-3 (4), 3-4 (1), 2-4 (5). Kruskal takes 1-2 (1), then 3-4 (1), then 2-3 (2) — total 4 — and correctly skips 1-3 (4) because 1 and 3 are already connected through 1-2-3.
MST vs shortest path, and common mistakes
Do not confuse the MST with shortest paths from a source: Dijkstra minimises the distance from one root to each vertex; an MST minimises the total weight of the whole tree, and the path between two vertices inside an MST is generally not their shortest path. The algorithms look similar (both use heaps and greedily take cheap edges) but optimise different quantities — an interview favourite.
Common mistakes: (1) running Kruskal without sorting, or stopping before checking that V - 1 edges were actually added (disconnected input); (2) a DSU find without path compression degrading on long chains; (3) in Prim's, pushing edges but forgetting the visited check on pop, which adds cycle-forming edges; (4) assuming the MST is unique — it is unique only if all edge weights are distinct; equal weights can give several MSTs with the same total weight.
Key points
- A spanning tree connects all V vertices with exactly V - 1 edges and no cycles; the MST minimises total weight.
- Cut property: the cheapest edge crossing any cut is always safe to include — both algorithms are this rule applied repeatedly.
- Kruskal: sort edges, add those joining different DSU components; O(E log E), dominated by the sort.
- Prim: grow one tree with a min-heap of frontier edges; O(E log V), better for dense graphs.
- MST total weight is unique even when the tree is not; MST paths are not shortest paths — that is Dijkstra's job.