Skip to content

Lesson 24 of 40Graphs in depth

Minimum Spanning Trees

Connect every node at the lowest total cost with Kruskal or Prim, know why greedy is safe here, and handle the follow-ups.

15 min read0/5 questions

Your company is opening six offices and needs to link them with leased fibre. Every possible link has a quote. You need every office reachable from every other, and you want to pay as little as possible in total. You do not need a direct link between each pair; traffic can hop through other offices. The cheapest set of links that still connects everyone is a minimum spanning tree, and two short greedy algorithms find it.

Interviewers use MST problems (Min Cost to Connect All Points, Connecting Cities With Minimum Cost, Optimize Water Distribution) to check that you can spot the pattern behind the story, pick between Kruskal and Prim for the graph's shape, and explain why a greedy choice is correct here when it so often is not.

What a minimum spanning tree is

Take a connected, undirected, weighted graph with V nodes. A spanning tree is a subset of its edges that connects all V nodes and has no cycle. Two facts follow from "connected with no cycle":

  • It has exactly V − 1 edges. One fewer and something is cut off; one more and you have a cycle.
  • There is exactly one path between any two nodes.

A minimum spanning tree is a spanning tree whose total edge weight is as small as possible. If the graph is disconnected, no spanning tree exists. The algorithms then produce a minimum spanning forest, one tree per component, and your code should detect that and report it (usually by returning -1).

Where it shows up beyond interviews:

  • Network design: cables, pipes, roads, power lines. The original 1926 motivation was Borůvka's electrical network in Moravia.
  • Clustering: run Kruskal but stop when k groups remain. The result maximises the gap between the closest pair of points in different groups (single-linkage clustering).
  • Approximation: walking an MST gives a route at most twice the optimal for the travelling salesperson problem when distances obey the triangle inequality.

The cut property: why greedy is safe here

A greedy algorithm is only correct when you can argue that the greedy choice never hurts (the Greedy Algorithms lesson calls this an exchange argument). For MSTs that argument is the cut property.

Split the nodes into any two groups. That split is a cut, and some edges cross it. The cut property says: the lightest edge crossing any cut belongs to some MST. If that lightest edge is strictly lighter than every other crossing edge, it belongs to every MST.

The proof is a swap. Suppose an MST T does not contain the lightest crossing edge e. Add e to T. That creates a cycle, and that cycle must cross the cut a second time through some other edge f. Remove f. You have a spanning tree again, and since e weighs no more than f, it costs no more than T. So a minimum tree with e exists.

The mirror image is the cycle property: the strictly heaviest edge on any cycle is in no MST. You can always drop it and keep everything connected through the rest of the cycle.

Both algorithms below are just two different ways of picking a cut and taking its lightest edge, over and over, until V − 1 edges are chosen.

Quick check
Nodes are split into {A, B} and {C, D, E}. The edges crossing this cut weigh 9, 4 and 6, and no other crossing edges exist. What can you say for certain?
Need a nudge? A hint rules out a wrong answer.

Kruskal: cheapest edges first

Kruskal looks at the whole edge list at once:

  1. Sort edges by weight.
  2. Walk the list. For each edge (u, v), if u and v are already connected by edges you picked, skip it, because it would close a cycle. Otherwise take it.
  3. Stop after V − 1 edges.

"Already connected?" is exactly what union-find answers, in near-constant time. Each taken edge is the lightest edge across the cut between u's current group and everything else, so the cut property says it is safe.

Kruskal on six offices
ABCDEF732485169

currentwaitingdone

Sorted edges: 1 (D-E), 2 (B-C), 3 (A-C), 4 (B-D), 5 (C-E), 6 (D-F), 7, 8, 9. Every office starts in its own group.

1/7
Python
class DSU: """Union-find with path compression AND union by size: near O(1) per call.""" 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]] # path halving x = self.parent[x] return x def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False # would close a cycle 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(n, edges): """edges: (weight, u, v). Returns (total, chosen) or None if disconnected.""" dsu = DSU(n) total, chosen = 0, [] for w, u, v in sorted(edges): if dsu.union(u, v): total += w chosen.append((u, v, w)) if len(chosen) == n - 1: break # early exit return (total, chosen) if len(chosen) == n - 1 else None def clusters(n, edges, k): """Single-linkage clustering: merge cheapest pairs until k groups remain. Returns the spacing: the smallest distance between two different groups.""" dsu, groups = DSU(n), n for w, u, v in sorted(edges): if dsu.find(u) != dsu.find(v): if groups == k: return w # first edge we refuse to take dsu.union(u, v) groups -= 1 return None A, B, C, D, E, F = range(6)offices = [(7, A, B), (3, A, C), (2, B, C), (4, B, D), (8, C, D), (5, C, E), (1, D, E), (6, D, F), (9, E, F)]total, chosen = kruskal(6, offices)assert total == 16 and len(chosen) == 5assert kruskal(4, [(1, 0, 1), (2, 2, 3)]) is None # two islands: no spanning treeassert kruskal(3, [(-5, 0, 1), (2, 1, 2), (1, 0, 2)])[0] == -4 # negative weights are fineassert clusters(6, offices, 2) == 6 # {A..E} and {F}, 6 apartprint("total:", total, "edges:", chosen)
Output
Press Run (⌘ Enter) to see what happens.

Sorting dominates: O(E log E), which is the same as O(E log V) because E is at most V², so log E is at most 2 log V. Union-find adds O(E · α(V)), where α is the inverse Ackermann function, at most 4 for any input that fits in the universe. That bound needs both path compression and union by size or rank; with only one of them it degrades to O(log V) per operation. The Union-Find in Depth lesson walks through why.

Predict the outputPython

Using kruskal above, what does this print?

edges = [(4, 0, 1), (1, 1, 2), (3, 0, 2), (2, 2, 3), (5, 1, 3)]
print(kruskal(4, edges)[0])
Need a nudge? Hints walk you through it.
Put it in order5 steps

Put Kruskal's algorithm in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Prim: grow one tree outward

Prim starts from any node and grows a single tree. At every step it takes the cheapest edge that leaves the tree. The cut is "nodes in the tree" versus "nodes outside", so again the cut property makes each choice safe.

The usual implementation is the lazy heap version. Push every edge leaving a newly added node onto a min-heap. Pop the cheapest. If its far end is already in the tree, the entry is stale: skip it. Otherwise add that node and push its edges. It looks almost exactly like Dijkstra, which is the source of a classic bug covered below.

Lazy Prim from A (labels = cheapest known edge into the tree)
AB7C3DEF732485169

currentwaitingdone

Tree = {A}. Push A's edges. Heap: (3, C), (7, B).

1/6
Python
import heapq def prim(n, adj, start=0): """adj[u] = [(w, v), ...]. Returns the MST weight, or None if disconnected.""" in_tree = [False] * n heap = [(0, start)] total = added = 0 while heap and added < n: w, u = heapq.heappop(heap) if in_tree[u]: continue # stale entry: u joined through a cheaper edge in_tree[u] = True total += w added += 1 for w2, v in adj[u]: if not in_tree[v]: heapq.heappush(heap, (w2, v)) # edge weight, NOT total distance return total if added == n else None def build(n, edges): adj = [[] for _ in range(n)] for w, u, v in edges: adj[u].append((w, v)) adj[v].append((w, u)) return adj A, B, C, D, E, F = range(6)offices = [(7, A, B), (3, A, C), (2, B, C), (4, B, D), (8, C, D), (5, C, E), (1, D, E), (6, D, F), (9, E, F)]assert prim(6, build(6, offices)) == 16assert all(prim(6, build(6, offices), s) == 16 for s in range(6)) # any start worksassert prim(4, build(4, [(1, 0, 1), (2, 2, 3)])) is Noneprint("prim total:", prim(6, build(6, offices)))
Output
Press Run (⌘ Enter) to see what happens.

The heap can hold up to E entries, so this is O(E log E) = O(E log V), the same order as Kruskal. An "eager" variant with a decrease-key heap stores at most V entries, but Python's heapq has no decrease-key, so the lazy version is what you write in interviews.

Dense graphs: Prim without a heap

Min Cost to Connect All Points gives you up to 1,000 points and says the cost between two points is their Manhattan distance. There is no edge list: every pair is an edge. That is a complete graph with about 500,000 edges.

Kruskal would build and sort all of them: O(V² log V) time and O(V²) memory. Heap Prim pushes O(V²) entries too. The better tool is the oldest version of Prim: keep an array best[v], the cheapest known edge from the tree to v. Each round, scan the array for the closest outside node (O(V)), add it, and update best for every other outside node (O(V)). V rounds give O(V²) time and O(V) memory, with no edge list at all. For a complete graph you cannot beat O(V²) by much anyway, because the input implicitly has V² edges.

Python
def min_cost_connect_points(points): n = len(points) in_tree = [False] * n best = [float("inf")] * n # cheapest edge from the tree to each point best[0] = 0 total = 0 for _ in range(n): u = min((i for i in range(n) if not in_tree[i]), key=best.__getitem__) in_tree[u] = True total += best[u] ux, uy = points[u] for v in range(n): if not in_tree[v]: d = abs(ux - points[v][0]) + abs(uy - points[v][1]) if d < best[v]: best[v] = d return total def kruskal_points(points): """Reference answer: build every edge and run Kruskal.""" n = len(points) parent = list(range(n)) def find(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x edges = sorted((abs(a[0] - b[0]) + abs(a[1] - b[1]), i, j) for i, a in enumerate(points) for j, b in enumerate(points) if i < j) total = 0 for w, i, j in edges: ri, rj = find(i), find(j) if ri != rj: parent[ri] = rj total += w return total assert min_cost_connect_points([[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]) == 20assert min_cost_connect_points([[3, 12], [-2, 5], [-4, 1]]) == 18assert min_cost_connect_points([[0, 0]]) == 0 import randomrng = random.Random(7)for _ in range(200): pts = [[rng.randint(-50, 50), rng.randint(-50, 50)] for _ in range(rng.randint(1, 30))] assert min_cost_connect_points(pts) == kruskal_points(pts)print(min_cost_connect_points([[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]))
Output
Press Run (⌘ Enter) to see what happens.

The random cross-check against a second, independent algorithm is a habit worth copying. When two different methods agree on 200 random inputs, an off-by-one in either is very unlikely to survive.

Choosing between them

SituationPickCost
You are handed an edge list, graph is sparseKruskalO(E log E)
Edges arrive pre-sorted, or you need clustering into k groupsKruskalnear O(E) / stop early
Adjacency list, sparse or medium densityPrim with a heapO(E log V)
Complete or implicit graph (all pairs of points)Prim with an arrayO(V²), O(V) memory
Extra "free" source like a well or power plantEither, after adding a virtual nodeas above

That last row is a common disguise. In Optimize Water Distribution, each house can dig its own well at a cost or connect to a neighbour by pipe. Add a virtual node 0 for "the water supply" with an edge to each house weighted by its well cost, then take the MST of the whole thing.

Quick check
You have 2,000 points and the cost of linking any two is their Euclidean distance. Which approach fits best?
Need a nudge? A hint rules out a wrong answer.

Follow-ups interviewers ask

Is the MST unique? If all edge weights are distinct, yes. With ties there can be several, but every MST has the same total weight, and in fact the same multiset of edge weights.

Do negative weights break it? No. Unlike Dijkstra, MST algorithms only compare edges with each other, so adding a constant to every weight changes nothing. Negative weights are fine.

Maximum spanning tree? Sort descending in Kruskal, or negate every weight. A related trick: the MST also minimises the largest edge on the path between any two nodes (a minimum bottleneck path), which is one way to solve Swim in Rising Water from the Shortest Paths lesson.

Is the MST a shortest-path tree? No, and this is the follow-up people get wrong. The MST minimises the sum of all edges. A shortest-path tree from a source minimises the distance from that source to each node. They usually differ:

Same graph, two different trees
ABC223

currentwaitingdone

MST: A-B (2) and B-C (2), total 4. But the path from A to C inside this tree costs 4.

1/2
Quick check
A delivery firm wants each depot reachable from headquarters by the cheapest possible route. A colleague suggests computing the minimum spanning tree. What is the problem?
Need a nudge? A hint rules out a wrong answer.
Critical and pseudo-critical edges

A harder follow-up (Find Critical and Pseudo-Critical Edges in MST) asks which edges are in every MST (critical) and which are in some but not all (pseudo-critical). The interview-friendly approach reuses Kruskal as a black box, which is fine for E up to a few hundred:

  • First compute the MST weight base.
  • An edge is critical if building the MST without it gives a larger total, or no spanning tree at all.
  • Otherwise it is pseudo-critical if forcing it in first (union its endpoints, add its weight) still achieves base.

Each check is one Kruskal pass, so the whole thing is O(E² α(V)) after sorting once.

Python
def find_critical_edges(n, edges): order = sorted(range(len(edges)), key=lambda i: edges[i][2]) def mst(skip=-1, force=-1): parent = list(range(n)) def find(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x total, used = 0, 0 if force != -1: u, v, w = edges[force] parent[find(u)] = find(v) total, used = w, 1 for i in order: if i == skip: continue u, v, w = edges[i] ru, rv = find(u), find(v) if ru != rv: parent[ru] = rv total += w used += 1 return total if used == n - 1 else float("inf") base = mst() critical, pseudo = [], [] for i in range(len(edges)): if mst(skip=i) > base: critical.append(i) elif mst(force=i) == base: pseudo.append(i) return [critical, pseudo] edges = [[0, 1, 1], [1, 2, 1], [2, 3, 2], [0, 3, 2], [0, 4, 3], [3, 4, 3], [1, 4, 6]]assert find_critical_edges(5, edges) == [[0, 1], [2, 3, 4, 5]]assert find_critical_edges(4, [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 3, 1]]) == [[], [0, 1, 2, 3]]print(find_critical_edges(5, edges))
Output
Press Run (⌘ Enter) to see what happens.
Key terms
spanning tree
A set of V - 1 edges that connects all V nodes with no cycle. There is exactly one path between any two nodes.
minimum spanning tree
A spanning tree with the smallest total edge weight. Unique when all weights are distinct.
cut property
The lightest edge crossing any split of the nodes into two groups belongs to some MST. It is why Kruskal and Prim are correct.
cycle property
The strictly heaviest edge on any cycle belongs to no MST.
Kruskal's algorithm
Sort edges, take each one unless union-find says its endpoints are already connected. O(E log E).
Prim's algorithm
Grow one tree by repeatedly adding the cheapest edge leaving it. O(E log V) with a heap, O(V squared) with an array.
shortest-path tree
The tree of shortest routes from one source (what Dijkstra builds). Usually not the MST.