Minimum Spanning Trees
Connect every vertex at minimum total cost — Kruskal's and Prim's algorithms and the cut property behind them.
Given a connected, weighted, undirected graph, a spanning tree connects all V vertices with exactly V − 1 edges and no cycles. A minimum spanning tree (MST) is one whose total edge weight is smallest. Think: lay cable to connect every building as cheaply as possible.
The cut property
Split the vertices into any two groups. The cheapest edge crossing the split belongs to some MST. Both classic algorithms are just different ways of repeatedly applying this greedy rule.
Kruskal's algorithm
Sort all edges by weight. Add each edge unless it would create a cycle — which Union-Find detects in near-O(1). Stop at V − 1 edges.
int kruskal(int n, int[][] edges) { // edges: {u, v, w}
Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
DSU dsu = new DSU(n);
int total = 0, used = 0;
for (int[] e : edges) {
if (dsu.union(e[0], e[1])) { // false → would form a cycle
total += e[2];
if (++used == n - 1) break;
}
}
return used == n - 1 ? total : -1; // -1: graph not connected
}def kruskal(n, edges): # edges: [(u, v, w)]
dsu = DSU(n)
total = used = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
if dsu.union(u, v):
total += w
used += 1
if used == n - 1:
break
return total if used == n - 1 else -1function kruskal(n: number, edges: [number, number, number][]): number {
edges.sort((a, b) => a[2] - b[2]);
const dsu = new DSU(n);
let total = 0, used = 0;
for (const [u, v, w] of edges) {
if (dsu.union(u, v)) {
total += w;
if (++used === n - 1) break;
}
}
return used === n - 1 ? total : -1;
}Time: O(E log E) for sorting — dominated by the sort.
Prim's algorithm
Grow a single tree from a start vertex. Repeatedly add the cheapest edge leaving the tree, using a min-heap — structurally almost identical to Dijkstra, but the key is the edge weight, not the path distance.
int prim(List<List<int[]>> adj) { // adj[u] = {v, w}
int n = adj.size(), total = 0;
boolean[] inTree = new boolean[n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
pq.offer(new int[]{0, 0});
while (!pq.isEmpty()) {
int[] top = pq.poll();
int u = top[0];
if (inTree[u]) continue;
inTree[u] = true;
total += top[1];
for (int[] e : adj.get(u)) if (!inTree[e[0]]) pq.offer(new int[]{e[0], e[1]});
}
return total;
}import heapq
def prim(adj): # adj[u] = [(v, w)]
n, total = len(adj), 0
in_tree = [False] * n
pq = [(0, 0)] # (weight, vertex)
while pq:
w, u = heapq.heappop(pq)
if in_tree[u]:
continue
in_tree[u] = True
total += w
for v, wt in adj[u]:
if not in_tree[v]:
heapq.heappush(pq, (wt, v))
return totalfunction prim(adj: [number, number][][]): number {
const inTree = new Array(adj.length).fill(false);
const pq = new MinHeap<[number, number]>((a, b) => a[1] - b[1]); // [vertex, weight]
pq.push([0, 0]);
let total = 0;
while (pq.size) {
const [u, w] = pq.pop()!;
if (inTree[u]) continue;
inTree[u] = true;
total += w;
for (const [v, wt] of adj[u]) if (!inTree[v]) pq.push([v, wt]);
}
return total;
}Time: O(E log V) with a binary heap.
- Edge-centric: sort edges, add if no cycle
- Needs Union-Find
- Great for sparse graphs or an edge list
- Naturally handles forests (disconnected graphs)
- Vertex-centric: grow one tree
- Needs a priority queue
- Great for dense graphs (O(V²) with an array)
- Similar code to Dijkstra
Applications: network and circuit design, clustering (remove the k−1 heaviest MST edges to get k clusters), approximation for the travelling salesman problem (2× optimal for metric TSP), image segmentation.
- An MST connects all vertices with minimum total weight using V − 1 edges.
- The cut property justifies greedy choices.
- Kruskal: sort edges + Union-Find, O(E log E). Prim: heap from a start vertex, O(E log V).
- If all edge weights are distinct, the MST is unique.
QMin cost to connect all points (Manhattan distance).medium
It's a complete graph with V² edges. Prim's with an O(V²) array (no heap) is ideal for dense graphs: keep minDist[v] to the tree and pick the smallest each round.
QIs the shortest-path tree from Dijkstra the same as the MST?medium
No. Dijkstra minimises each vertex's distance from one source; the MST minimises the total weight of the tree. A triangle with edges A–B 2, B–C 2, A–C 3: from A, the shortest-path tree uses A–C (3), but the MST uses A–B and B–C (total 4 vs 5).