Minimum
Spanning Tree
Connect all nodes in a weighted graph at minimum total cost. Kruskal and Prim both solve this greedily in O(E log E) and O(E log V) — powering network design, clustering, and image segmentation.
What is a minimum spanning tree?
A minimum spanning tree (MST) connects all nodes of a weighted, undirected graph with the smallest possible total edge weight and no cycles, which is the cheapest way to wire everything together. Kruskal's algorithm sorts the edges by weight and adds each one that doesn't form a cycle (checked with union-find). Prim's algorithm grows the tree from one node using a priority queue.
function kruskal(n, edges) { // edges: [u, v, weight]
const uf = new UnionFind(n), mst = [];
for (const [u, v, w] of edges.toSorted((a, b) => a[2] - b[2])) {
if (uf.union(u, v)) mst.push([u, v, w]); // skip edges that make a cycle
if (mst.length === n - 1) break;
}
return mst;
}Kruskal — animated
// Array state
// Pseudocode
Understanding MST algorithms
What is an MST?
A spanning tree connects all V vertices with exactly V-1 edges and no cycles. The minimum spanning tree has the smallest total edge weight among all spanning trees.
Kruskal pseudocode
1// Kruskal — sort edges, add if no cycle2function kruskal(graph):3 edges = sorted(graph.edges, by=weight)4 uf = UnionFind(graph.vertices)5 mst = []6 for (w, u, v) in edges:7 if uf.find(u) != uf.find(v): // no cycle8 uf.union(u, v)9 mst.append((w, u, v))10 if len(mst) == V - 1: break11 return mst // O(E log E)
Prim pseudocode
1// Prim — grow MST one edge at a time2function prim(graph, start):3 inMST = Set()4 pq = MinHeap() // (weight, vertex, parent)5 pq.push((0, start, -1))6 mst = []7 while pq not empty:8 (w, u, parent) = pq.pop()9 if u in inMST: continue10 inMST.add(u)11 if parent != -1: mst.append((w, parent, u))12 for (v, weight) in graph[u].neighbors:13 if v not in inMST:14 pq.push((weight, v, u))15 return mst // O(E log V)
Complexity comparison
Linearithmic time
Linearithmic time
Linear time
🎯 Quick Check
Kruskal processes edge (3, A, B). find(A) == find(B). What happens?
Minimum Spanning Tree: summary
Key points
- An MST of n nodes always has n − 1 edges.
- Kruskal is O(E log E) and suits sparse graphs; Prim with a heap is O(E log V).
- Uses: network cabling, road planning, clustering and approximation algorithms.
Frequently asked questions
›Is the minimum spanning tree the same as the shortest path tree?
No. An MST minimises the total weight of all edges; Dijkstra's shortest path tree minimises the distance from one source to each node.