Learn the pattern · ~15 min
Minimum Spanning Tree
also called Kruskal, Prim
Take edges cheapest first, and keep an edge only if it joins two pieces that aren't connected yet. Stop at n − 1 edges.
Reach for it when you read
- +"Minimum total cost so that every city / point / house is connected": the MST definition in disguise.
- +Points on a plane with a distance cost between every pair: an MST of the complete graph (Prim's in O(n²)).
- +"Build a well or lay a pipe": a made-up node joined to every house turns the well cost into an edge.
- +Minimise the largest edge on a path, or answer "connected using only edges ≤ L?": add edges cheapest first and stop early.
- +Your brute force would try every set of n − 1 edges that connects the graph.
Not this one when
- ×The cheapest route from s to t: shortest path (Dijkstra). An MST minimises the whole network's total, not one path's length.
- ×Only "are these connected?" or "how many groups?" with no costs: plain union-find or BFS.
- ×Edges are one-way and you need a cheapest tree rooted at one node: that's an arborescence (Edmonds), not Kruskal or Prim.
Learn Minimum Spanning Tree
First, what is a "minimum spanning tree"?
Towns, and the roads you could build between them, each with a cost:
- A tree connects its nodes with no cycle. On n nodes it has exactly n − 1 edges: four towns need 3 roads, and a fourth would close a loop.
- Spanning means it reaches every node.
- Minimum means, of all the spanning trees, the one with the smallest total cost.
So a minimum spanning tree (MST) is the cheapest way to connect everything. Two greedy methods build it: Kruskal's and Prim's.
Kruskal's, step by step
Six nodes, nine possible edges, sorted by cost: 1–3 (1), 2–4 (2), 2–3 (3), 5–6 (3), 1–2 (4), 3–4 (5), 4–5 (6), 3–5 (7), 4–6 (8). The rule is one line:
Take the edges cheapest first. Skip any edge whose two ends are already connected.
| edge (cost) | what happens | total | pieces after |
|---|---|---|---|
| 1–3 (1) | different pieces: add | 1 | {1,3} {2} {4} {5} {6} |
| 2–4 (2) | different pieces: add | 3 | {1,3} {2,4} {5} {6} |
| 2–3 (3) | joins {2,4} with {1,3} | 6 | {1,2,3,4} {5} {6} |
| 5–6 (3) | different pieces: add | 9 | {1,2,3,4} {5,6} |
| 1–2 (4) | 1 and 2 already share a piece: a cycle, skip | 9 | same |
| 3–4 (5) | same piece again, skip | 9 | same |
| 4–5 (6) | joins the last two pieces | 15 | {1,2,3,4,5,6} |
| 3–5 (7), 4–6 (8) | one piece already, skip | 15 | same |
Five edges for six nodes, total 15: the cheapest of this graph's 55 spanning trees (they cost 15 to 28), found without listing any.
The code for it
int findRoot(vector<int>& p, int x) {
while (p[x] != x) x = p[x] = p[p[x]]; // up to the root, shortening the path
return x;
}
// nodes 1..n, edges {u, v, w}; -1 if not connected
long long kruskal(int n, vector<array<int, 3>> edges) {
sort(edges.begin(), edges.end(), [](auto& a, auto& b) { return a[2] < b[2]; });
vector<int> p(n + 1);
iota(p.begin(), p.end(), 0); // every node starts as its own piece
long long total = 0;
int used = 0;
for (auto [u, v, w] : edges) {
int a = findRoot(p, u), b = findRoot(p, v);
if (a == b) continue; // same piece: this edge would close a cycle
p[a] = b; // join the two pieces
total += w;
used++;
}
return used == n - 1 ? total : -1;
}You don't need to memorise this. It's the table above: sort, skip edges inside one piece, join the rest.
Why union-find? Kruskal's keeps asking "are u and v in the same piece?" Each piece has one root: two nodes are together when their roots match, and joining is one assignment. With the path shortening, each call is O(log n) amortised, near O(1) in practice.
Fine, but how does this help us?
A classic: Min Cost to Connect All Points. Points [0,0], [1,3], [4,1], [5,5], [2,6]; joining two costs their Manhattan distance, |x₁ − x₂| + |y₁ − y₂|. What's the cheapest way to connect them all?
That is an MST, on a graph where every pair is an edge. By hand, cheapest pairs first:
| pair | cost | how you decided |
|---|---|---|
| [0,0]–[1,3] | 4 | cheapest, take it |
| [1,3]–[2,6] | 4 | [2,6] is new, take it |
| [5,5]–[2,6] | 4 | [5,5] is new, take it |
| [0,0]–[4,1] | 5 | [4,1] is the last one left, take it |
| everything else | 5 to 10 | both ends already connected |
The answer is 17.
The brute force
Try every set of edges and keep the cheapest one that makes a tree:
int bruteForce(const vector<vector<int>>& pts) {
int n = pts.size(), best = INT_MAX;
vector<array<int, 3>> e; // every pair of points is an edge
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
e.push_back({i, j, abs(pts[i][0] - pts[j][0]) + abs(pts[i][1] - pts[j][1])});
for (int mask = 0; mask < (1 << e.size()); mask++) {
vector<int> p(n);
iota(p.begin(), p.end(), 0);
int total = 0, joins = 0;
for (int k = 0; k < (int)e.size(); k++)
if (mask >> k & 1) {
int a = findRoot(p, e[k][0]), b = findRoot(p, e[k][1]);
if (a == b) { joins = -1; break; }
p[a] = b, total += e[k][2], joins++;
}
if (joins == n - 1) best = min(best, total); // a spanning tree
}
return best;
}It returns 17 after trying all 1,024 sets of the 10 pairs. But 8 points (28 pairs, 2.7 × 10⁸ sets) already take 11 s, and the problem allows 1000 points. Time limit exceeded.
The one thought that fixes it: the cut property
Split the nodes into any two groups. The cheapest edge between the two groups is safe: some minimum spanning tree uses it.
Check it on our points. Put [0,0] alone in one group, the other four in the other. The edges across are 4 (to [1,3]), 5 (to [4,1]), 8 (to [2,6]) and 10 (to [5,5]). The cheapest is 4.
Take any spanning tree that doesn't use the 4-edge. It still has a route from [0,0] to [1,3], and that route leaves [0,0] by another crossing edge, say the 5 to [4,1].
- Add the 4-edge. With that route it makes a cycle, which crosses between the groups twice: on the 4 and on the 5.
- Remove the 5. The cycle is gone, everything is still connected: a spanning tree again.
- Its total changed by 4 − 5 = −1. If the other edge had cost 4 too, by 0.
Either way it's never worse, so the cheapest crossing edge can always be in the answer.
So both greedy methods are right. Kruskal's: when it adds 4–5 (6), split the nodes as {1,2,3,4} against {5,6}. The edges across cost 6, 7 and 8: 6 is the cheapest, so it's safe. Prim's uses the split "in the tree so far" against "not yet", and always adds the cheapest edge leaving the tree.
On points Prim's fits better: it never sorts all n² pairs. Keep d[v], the cheapest link from the tree to each outside point:
int minCostConnectPoints(const vector<vector<int>>& pts) {
int n = pts.size(), total = 0;
vector<int> d(n, INT_MAX); // d[v] = cheapest edge from the tree to v
vector<bool> in(n, false);
d[0] = 0; // start the tree at point 0
for (int k = 0; k < n; k++) {
int u = -1;
for (int i = 0; i < n; i++) // the outside point with the cheapest link
if (!in[i] && (u == -1 || d[i] < d[u])) u = i;
in[u] = true;
total += d[u];
for (int v = 0; v < n; v++) // u joined: its edges may be cheaper links
if (!in[v]) d[v] = min(d[v], abs(pts[u][0] - pts[v][0]) + abs(pts[u][1] - pts[v][1]));
}
return total;
}Dry run
The same five points, starting from [0,0]:
| takes | cost | total | cheapest link to each outside point |
|---|---|---|---|
| [0,0] | 0 | 0 | [1,3] 4, [4,1] 5, [5,5] 10, [2,6] 8 |
| [1,3] | 4 | 4 | [4,1] 5, [5,5] 6, [2,6] 4 |
| [2,6] | 4 | 8 | [4,1] 5, [5,5] 4 |
| [5,5] | 4 | 12 | [4,1] 5 |
| [4,1] | 5 | 17 | none |
17, the same answer as the brute force. Watch [5,5]: its link drops from 10 to 6 to 4 as closer points join.
Why it's fast
Prim's on points: n rounds, each scanning n points to pick one and update the rest. That's O(n²), 10⁶ steps for n = 1000, and O(n) space.
Kruskal's: the sort, then two cheap findRoot calls per edge: O(E log E).
From every set of edges down to n² steps, by always taking the cheapest edge across a split.
A well or a pipe? Add a made-up node
Each house digs a well or is piped to a neighbour. Make every well an edge to one made-up node, then run plain MST:
vector<array<int, 3>> edges = pipes;
for (int i = 1; i <= n; i++)
edges.push_back({n + 1, i, wells[i - 1]}); // a well = a pipe to node n + 1
long long answer = kruskal(n + 1, edges);Wells [5, 2, 4], pipes 1–2 (1), 2–3 (3), 1–3 (6): the MST takes 1–2, house 2's well and 2–3, total 6.
Remember this
- "Minimum total cost so that everything is connected" is MST.
- Kruskal's: sort, union-find, skip same-piece edges. Prim's: grow one tree, cheapest link each round. All pairs are edges: Prim's O(n²). Sparse: Kruskal's, or Prim's with a min-heap.
- Fewer than n − 1 edges added means the graph isn't connected: return −1.
- MST minimises the total, not one route: the cheapest s-to-t path is Dijkstra.
Practise it on Connecting Cities With Minimum Cost, then Min Cost to Connect All Points (build the edges), Optimize Water Distribution in a Village (the made-up node), Path With Minimum Effort (stop Kruskal's once start and end share a piece) and Find Critical and Pseudo-Critical Edges (rerun Kruskal's without each edge, then forcing it in).
Below, watch Connecting Cities With Minimum Cost run line by line.
Watch it work, line by line
Connecting Cities With Minimum Cost ↗, n = 5, cables = [1,2,3] [1,3,1] [2,3,7] [2,4,4] [3,4,2] [4,5,5] [3,5,6] → 11. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Does every node have to end up connected, with each link paid for once, and is the total cost (not one pair's distance) what you're minimising?
Reach for it when
- +connect all points/cities with minimum cost
- +minimax edge between two vertices (bottleneck path lies on MST)
- +Kruskal O(E log E); Prim O(V2) for dense complete graphs
It fails when
- ×The graph is directeduse Minimum arborescence (a different algorithm)
- ×You want shortest distances from a source (a shortest-path tree is not an MST)use Dijkstra
- ×You think MST minimises each pairwise distance — it only minimises the totaluse Shortest paths for pairwise distances
- ×Only some vertices must be connected (Steiner tree)use Not an MST problem
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why is the cheapest edge between two separate pieces always safe to take?Reveal
The cut property: some edge must cross between the pieces, and swapping any crossing edge for the cheapest one keeps the tree connected and never costs more.
2In Kruskal, what does
find(u) == find(v)tell you?Revealu and v are already connected, so the edge would close a cycle. Skip it.
3How do you know the graph was disconnected?Reveal
You finished the edge list with fewer than n − 1 edges bought.
Practice ladder
- 1Connecting Cities With Minimum Costthe hookMedium
- 2Road Reparationplain KruskalMedium
- 3Redundant Connectionunion-find halfMedium
- 4Min Cost to Connect All Pointsbuild the edgesMedium
- 5Optimize Water Distribution in a Villagevirtual nodeHard
- 6Path With Minimum Effortstop earlyMedium
- 7Checking Existence of Edge Length Limited Pathsmany limitsHard
- 8Find Critical and Pseudo-Critical Edges in Minimum Spanning Treewhich edges matterHard
Finished Minimum Spanning Tree? Mark it done and Lessgo moves you to the next step.