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.
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.
Kruskal: cheapest edges first
Kruskal looks at the whole edge list at once:
- Sort edges by weight.
- Walk the list. For each edge
(u, v), ifuandvare already connected by edges you picked, skip it, because it would close a cycle. Otherwise take it. - 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.
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.
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.
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])
Put Kruskal's algorithm in order.
- Tap the steps below in the right order.
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.
Tree = {A}. Push A's edges. Heap: (3, C), (7, B).
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.
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
| Situation | Pick | Cost |
|---|---|---|
| You are handed an edge list, graph is sparse | Kruskal | O(E log E) |
| Edges arrive pre-sorted, or you need clustering into k groups | Kruskal | near O(E) / stop early |
| Adjacency list, sparse or medium density | Prim with a heap | O(E log V) |
| Complete or implicit graph (all pairs of points) | Prim with an array | O(V²), O(V) memory |
| Extra "free" source like a well or power plant | Either, after adding a virtual node | as 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.
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:
MST: A-B (2) and B-C (2), total 4. But the path from A to C inside this tree costs 4.
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.
Press Run (⌘ Enter) to see what happens.- 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.