Six towns, ten possible cables. The five cheapest cables cost 15, but they close a loop and leave one town dark. Kruskal and Prim each find the cheapest network that reaches every town: 17.
Pick a rule and press Play. Watch which cables each rule takes, in which order. Then we build, piece by piece, the cut property that makes greed safe, Kruskal, Prim, their costs, and three uses.
You need a little Python and the idea of a graph (dots joined by lines). Greedy algorithms and disjoint sets help. We build the rest from zero.
Based on Chapter 23, Minimum Spanning Trees, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Elementary Graph Algorithms. Next: Single-Source Shortest Paths.
Illustrative network: we made up the towns and the ten prices, and every chapter uses them. Green cables stay. A red cable closes a loop. Prim starts at town A.
Chapter 0
Connect every town for the least money, and see why the cheapest cables alone fail
You lay fibre between six towns, A to F. Surveyors priced ten possible routes. Every town must reach every other town through some chain of cables. You want the smallest total bill.
Model it as a graph: each town is a vertex, each route is an edge, and each price is the edge's weight. A set of edges that reaches every vertex and has no loop is a spanning tree. The spanning tree with the smallest total weight is the minimum spanning tree, or MST.
A spanning tree on n towns always has n − 1 edges. With fewer, some town is cut off. One more edge closes a loop, and any cable on a loop can go without cutting anyone off. So six towns need exactly five cables. Which five?
Tap a cable on the map or a chip below to take it or drop it. Try to reach all six towns for the smallest bill.
Illustrative prices. Green: your cable is in a network that spans and has no loop. Red: this cable closes a loop.
Take the cheapest five: 1, 2, 3, 4 and 5. They cost 15. But B-C closes the loop A-B-C, and town E gets nothing. A good rule must take cheap edges and also refuse loops.
Why not test every tree? Count them. In a complete graph, every pair of the n towns has an edge. Call the number of its spanning trees τ, said "tau". Cayley's formula gives it.
Tau of K-n equals n to the power n minus two.
Multiply the town count n by itself n − 2 times. The result is how many different spanning trees a brute-force search must price.
n = 5: 5 × 5 × 5 = 125 trees. n = 10: 100,000,000. n = 20: about 2.6 × 1023. Our six towns have only ten routes and still 114 spanning trees. The cheapest costs 17.
The failure. Symptom: your network costs more than it should. Measure: count its edges; n or more edges on n towns means a loop. Fix: find the loop and remove its most expensive cable.
Chapter 1
Split the towns into two groups, and prove that the cheapest cable across the split is always safe
Greedy rules often fail. Here one fact makes greed safe. Split the towns into two groups, S and the rest. That split is a cut. An edge with one end in each group crosses the cut. The cheapest crossing edge is the light edge.
The cut property (CLRS Theorem 23.1): take the edges you have chosen so far, all inside some MST. Pick a cut that none of them crosses. Then the light edge of that cut is in some MST too. CLRS calls such an edge safe.
Tap towns to move them to side S (purple). Thick edges cross the cut. The warm one is the light edge.
Illustrative prices. With all ten prices different, every light edge you can find is in the one MST: turn on the MST to check.
Why is it true? Every spanning tree crosses every cut, or the two groups stay apart. Say a minimum tree T crosses only with heavier edges.
Call the light edge (u, v). Adding (u, v) to T closes one loop. The loop crosses the cut twice: once at (u, v) and once at a tree edge (x, y). Remove (x, y) and call the new tree T′. Write w(·) for total weight.
W of T-prime equals w of T, minus w of x-y, plus w of u-v.
Start from the bill w(T). Remove the cable (x, y) and add the light cable (u, v). Because w(u, v) is at most w(x, y), the bill w(T′) does not go up. So T′ is also a minimum tree, and it holds the light edge.
Cut S = {A, C}. The light edge is A-B, 4. Take a tree T that uses B-C, 5, instead: w(T) = 1 + 2 + 3 + 5 + 7 = 18. The swap gives w(T′) = 18 − 5 + 4 = 17, the true minimum.
This gives CLRS's generic MST method. Every algorithm in this lesson is one version of it.
The failure. Symptom: the method adds an edge whose two ends already connect, and a loop appears. Measure: check whether a chosen edge crosses your cut. Fix: use only cuts that no chosen edge crosses. Then the light edge always joins two separate pieces.
Chapter 2
Rule out the edges no minimum tree uses, and learn when the answer is unique
The cut property says which edges to take. The cycle property says which to drop. On any loop, an edge heavier than every other edge of that loop is in no MST.
The proof is the same swap, run backwards. Say a tree holds that heaviest edge. Remove it, and the tree splits into two groups: a cut. The loop crosses that cut at least once more, at a lighter edge. Put the lighter edge in. The bill drops, so the first tree was not minimum.
Pick a loop. Its edges turn teal and its heaviest edge turns red. Turn on the MST to see that red is never in it.
Illustrative prices. The five triangles rule out B-C, C-D, C-F, B-E and E-F: exactly the five edges outside the MST.
Count it on our map. Five triangles rule out five edges. Ten edges minus five leaves five, and those five are the MST. Here the cycle property alone finds the answer.
One tree or many? If all weights differ, the MST is unique. With ties there can be several. Take a triangle with weights 1, 2 and 2: you can drop either 2, so there are two MSTs. Both cost 3. All MSTs of a graph have the same total and the same list of weights.
The MST has one more gift. On the tree route between two towns, the most expensive cable is as cheap as any route allows. B to E in the tree uses B-D 3 and D-E 7, so its worst cable is 7. Every route from B to E has a cable of 7 or more. This is the minimum bottleneck property.
The failure. Symptom: two runs of a correct program return different trees. Measure: compare the totals; equal totals mean ties, not a bug. Fix: break ties by edge index if you need the same tree every time.
Chapter 3
Sort every cable, then keep each one that joins two separate pieces
Kruskal's algorithm (1956) looks at edges, not towns:
Press Next. Teal is the edge under test. Green edges stay. A red edge would close a loop. The list shows the sorted order.
Illustrative prices. Kruskal stops after its fifth kept edge, so C-F, B-E and E-F are never tested.
Why is every kept edge safe? When Kruskal keeps (u, v), take the cut "u's piece against the rest". No kept edge crosses it. Any cheaper crossing edge came earlier, and Kruskal would have kept it. So (u, v) is the light edge, and the cut property applies. A skipped edge is the heaviest on the loop it would close, so the cycle property drops it.
| Edge | Weight | Action | Pieces after |
|---|---|---|---|
| D-F | 1 | keep | {D,F} {A} {B} {C} {E} |
| A-C | 2 | keep | {A,C} {D,F} {B} {E} |
| B-D | 3 | keep | {A,C} {B,D,F} {E} |
| A-B | 4 | keep | {A,B,C,D,F} {E} |
| B-C | 5 | skip: loop B-A-C | no change |
| C-D | 6 | skip: loop C-A-B-D | no change |
| D-E | 7 | keep | one piece; total 17 |
What does it cost? Call the number of edges E and the number of towns V. Sorting takes about E log₂ E comparisons. Each edge then needs two piece lookups. Chapter 4's union-find makes each lookup cost α(V), a number that is at most 4 in practice.
T-Kruskal equals big-O of E log E, plus big-O of E times alpha of V.
Sort the E edges once, then do two lookups for each edge. The sort term is larger, so Kruskal runs in O(E log E). That equals O(E log V), because E is less than V² and so log E is less than 2 log V.
With made-up sizes: V = 1,000 towns and E = 2,000 cables. The sort takes about 2,000 × 11 = 21,900 comparisons. The lookups take about 2 × 2,000 = 4,000 steps times a small constant.
The failure. Symptom: after all edges, you hold fewer than n − 1. Measure: count the kept edges. Fix: the graph is not connected; report the pieces. What you hold is a minimum spanning forest: one MST per piece.
Chapter 4
Answer "are these two towns already joined?" in a few pointer steps
Kruskal asks one question per edge: are u and v already in one piece? A fresh search answers it in O(V + E) steps, for every edge. Union-find answers it in a few pointer steps. The full lesson is CLRS 21: Disjoint Sets; here is the part Kruskal needs.
Each piece is a tree of parent pointers. The root names the piece. Find(x) walks up from x to its root. Union(x, y) hangs one root under the other. Two rules keep the trees flat:
Press Next. The forest shows each piece as a tree; warm rings are roots. Blue marks the path each Find walks. A purple cell is a pointer that just changed.
Union by rank and path compression are both on. On a tie in rank, the root of v goes under the root of u.
Follow the skip of B-C. After A-B, the pointers are B to D and D to A. Find(B) walks 2 hops to A, and compression points B straight at A. Find(C) walks 1 hop to A. Same root, so skip. All seven tests together walk 7 hops.
With both rules, m operations on n elements cost O(m α(n)) in total (CLRS Chapter 21). Kruskal does 2E Finds and V − 1 Unions, so its lookups cost O(E α(V)): the second term of Chapter 3's equation.
The failure. Symptom: Kruskal is slow on a big graph although the sort is fast. Measure: count the pointer hops per Find; a growing count means tall trees. Fix: add both rules.
Chapter 5
Start at one town and always add the cheapest cable that leaves the tree
Kruskal grows many pieces at once. Prim's algorithm grows one tree. Jarník found it in 1930, Prim again in 1957. Start at any town. At each step, add the cheapest edge with one end in the tree and one end outside. That edge is the light edge of the cut "tree against the rest", so the cut property makes it safe.
To find that edge fast, Prim keeps one number per outside town. Call the set of towns already in the tree S. For an outside town v, its key is the price of its cheapest cable into S.
Key of v equals the minimum, over u in S, of w of u-v.
For town v, look at every cable from v into the tree S. Keep the cheapest price as key[v]. When a new town u joins S, check only its cables. If w(u, v) is less than key[v], lower key[v] to w(u, v).
After A and C join, S = {A, C}. A has no cable to D, and C-D costs 6, so key[D] = 6. Then B joins, and B-D costs 3, so key[D] = min(6, 3) = 3.
Pick a start and press Next. Purple towns are in the tree. Blue dashed edges leave it; the warm one is the cheapest. The bars are the keys.
Illustrative prices. Both starts end with the same five edges, because all ten prices differ.
| Takes | Key | Joins by | Keys lowered |
|---|---|---|---|
| A | 0 | start | B ∞ to 4, C ∞ to 2 |
| C | 2 | A-C | D ∞ to 6, F ∞ to 8 |
| B | 4 | A-B | D 6 to 3, E ∞ to 9 |
| D | 3 | B-D | E 9 to 7, F 8 to 1 |
| F | 1 | D-F | none |
| E | 7 | D-E | none; total 17 |
Prim looks like Dijkstra's shortest-path algorithm (CLRS 24). One line differs. Prim compares w(u, v) with key[v]. Dijkstra compares d[u] + w(u, v), the whole trip from the start, with d[v]. Dijkstra's tree from A costs 19: it reaches E by B-E (9), because the trip A-B-E, 13, beats A-B-D-E, 14.
The failure. Symptom: your "MST" changes when you change the start town, and it costs more than Kruskal's. Measure: compare the totals of both algorithms. Fix: the key update adds up whole trips; make it the price of one cable.
Chapter 6
Count the steps for sparse and dense graphs, and pick the right tool
A sparse graph has few edges per town, like roads. A dense graph has nearly every pair joined, like the distances between 1,000 points. Both algorithms find the same tree; their costs differ.
Prim with a binary heap (a priority queue that returns the smallest key in log₂ V steps) does V "take the smallest" operations. It also does up to E key decreases, one per edge. Each operation costs about log₂ V.
T-Prim-heap equals big-O of V plus E, times log V.
Every town leaves the heap once, and every edge may lower one key once. That is V + E heap operations. Each costs log V steps, so multiply.
With made-up sizes: V = 1,000 and E = 2,000. (1,000 + 2,000) × 10 ≈ 29,900 steps. Kruskal sorts the same graph in about 21,900. On the complete graph, E = 499,500: the heap needs about 4,990,000 and Kruskal about 9,460,000.
A third version drops the heap. Keep the keys in a plain array and scan all V of them to find the smallest. V scans of V entries cost V² = 1,000,000 for 1,000 towns, whatever E is. On a complete graph that beats both.
Drag the number of towns and pick a density. The axis is logarithmic: each grid line is ten times the last.
Rough step counts: Kruskal E log₂ E, Prim with a heap (V + E) log₂ V, Prim with an array V². We ignore constants, so treat a gap under 2 times as a tie.
| Version | Running time | Best for |
|---|---|---|
| Kruskal + union-find | O(E log E) | sparse graphs, edges given as a list |
| Prim + binary heap | O((V + E) log V) | medium density, adjacency lists |
| Prim + plain array | O(V²) | complete or near-complete graphs |
| Prim + Fibonacci heap | O(E + V log V) | theory: best bound in CLRS 23.2 |
The failure. Symptom: an MST on 100,000 points runs out of memory. Measure: count the stored edges: 100,000 × 99,999 / 2 is about 5 billion. Fix: use array Prim and compute each distance when you need it; memory stays at O(V).
Chapter 7
Drag towns, run either algorithm, and watch the same tree appear by two routes
Now the map is yours. A cable can join any pair of towns, and it costs its straight-line length. Drag a town and the tree follows. Then play Kruskal and Prim on the same map and watch the order of their picks.
Drag a town. Pick an algorithm and press Play to watch it work. Faint lines are all possible cables.
Illustrative map, 4 to 14 towns. Lengths are in map units. Prim starts at town 1. Teal marks the edge under test.
Four things to try:
The failure. Symptom: on a perfect square of four towns, Kruskal and Prim draw different trees. Measure: compare totals; both are three sides. Fix: nothing is wrong: equal lengths make ties, and ties allow several MSTs (Chapter 2).
Chapter 8
Delete the k − 1 heaviest tree edges to split points into k groups that sit as far apart as possible
You have points on a map and want k groups. Build the MST. Delete its k − 1 heaviest edges. The pieces that remain are the groups. Statisticians call this single-linkage clustering.
The spacing of a grouping is the distance between the closest two points in different groups. Large spacing means well separated groups. The MST cut gives the largest spacing of any grouping into k groups (Kleinberg and Tardos, Algorithm Design, Section 4.7).
Sort the MST edge weights from heaviest down: d1, d2, and so on. Delete d1 to dk−1, and call the result C*.
Spacing of C-star equals d sub k minus one.
Delete the k − 1 heaviest tree edges. The last one you delete is dk−1, the lightest of them. No two points in different groups are closer than dk−1.
Our six towns: the MST edges weigh 7, 4, 3, 2 and 1. For k = 3, delete 7 and 4. The groups are {E}, {A, C} and {B, D, F}. Spacing = d2 = 4: the cheapest cable between groups is A-B, 4.
Why can no grouping do better? Take any other grouping C into k groups. It must split two points p and q that C* keeps together. The tree path from p to q uses only edges of weight dk−1 or less. Somewhere that path steps from one group of C to another. That step is a cross-group pair at distance dk−1 or less.
Drag k. Each step deletes the heaviest remaining tree edge (dashed). Colours mark the groups.
Illustrative points: three or four random blobs. The read-out checks the spacing against all pairs by brute force.
The failure. Symptom: one giant group and a few single points. Measure: look at group sizes; a thin line of points can join two blobs, called chaining. Fix: use a method that looks at whole groups, such as average linkage or k-means.
Chapter 9
Turn a tree into a sales tour at most twice the best, and grow every piece at once
A salesman must visit every city once and return home. Finding the shortest such tour is the travelling salesman problem. Nobody knows a fast exact method. Assume the triangle inequality: a direct trip is never longer than a detour. Then the MST gives a tour at most twice the best (CLRS Section 35.2):
W of MST is at most OPT, which is at most w of H, which is at most two times w of MST.
Remove one edge from the best tour and you get a spanning tree, so w(MST) is at most OPT. Walking down and back each tree edge costs 2 · w(MST). Skipping cities you already saw only shortens that walk, by the triangle inequality, which gives H.
Four cities on the corners of a square with side 1. The MST is three sides: 3. The best tour is 4. The preorder walk visits the corners in order and returns: H = 4. So 3 ≤ 4 ≤ 4 ≤ 6.
Pick a view. The bars compare the tree, the best tour, the tree tour H and twice the tree on one scale.
Illustrative random cities with straight-line distances, which obey the triangle inequality. The device finds the best tour by trying every order, so cities stop at 8.
Borůvka's algorithm (1926) is the oldest MST method. In each round, every piece picks its cheapest outgoing edge, and the round adds them all at once. On our towns, round 1 adds D-F 1, A-C 2, B-D 3 and D-E 7, leaving {A, C} and {B, D, E, F}. Round 2 adds A-B 4. Total 17.
Each round at least halves the number of pieces, so there are at most log₂ V rounds of O(E) work: O(E log V). The pieces choose independently, so a round splits well across many machines.
The failure. Symptom: the tree tour is more than twice the tree. Measure: test the triangle inequality on sample triples of costs. Fix: replace each cost with the shortest-path distance, which obeys it.
Chapter 10
Keep the terms, the numbers, the checks and the core code on one page
A minimum spanning tree joins every vertex for the least total weight, with n − 1 edges and no loop. The cut property makes the cheapest edge across any clean split safe. Kruskal sorts edges and uses union-find; Prim grows one tree with a priority queue. Both cost about O(E log V).
| Term | Meaning | Number on this page |
|---|---|---|
| Spanning tree | reaches every vertex, no loop, n − 1 edges | 114 trees for our 6 towns; the cheapest costs 17 |
| Cayley's formula | spanning trees of the complete graph: nn−2 | 125 for n = 5 |
| Light edge | cheapest edge across a cut | A-B, 4, for S = {A, C} |
| Cut property | a light edge of a clean cut is safe | swap: 18 − 5 + 4 = 17 |
| Cycle property | the strictly heaviest edge of a loop is in no MST | 5 triangles rule out 5 edges |
| Kruskal | sort, keep an edge when its ends are in different pieces | 7 tests, 5 keeps, 17 |
| Prim | grow one tree; key[v] = cheapest cable into the tree | order A, C, B, D, F, E; 17 |
| Shortest-path tree | Dijkstra's tree: short trips, not a small bill | 19 from A |
| Running times | Kruskal O(E log E), Prim heap O((V + E) log V), array O(V²) | 21,900 / 29,900 / 1,000,000 for V = 1,000, E = 2,000 |
| Spacing | closest pair across groups = dk−1 | 4 for k = 3 on our towns |
| Tree tour | w(MST) ≤ OPT ≤ w(H) ≤ 2 · w(MST) | 3 ≤ 4 ≤ 4 ≤ 6 on a unit square |
| Borůvka | every piece adds its cheapest edge each round | 2 rounds on our towns |
pythonimport heapq def kruskal(n, edges): # edges: [(w, u, v), ...] parent, rank = list(range(n)), [0] * n def find(x): while parent[x] != x: parent[x] = parent[parent[x]] # path halving x = parent[x] return x tree = [] for w, u, v in sorted(edges): ru, rv = find(u), find(v) if ru == rv: continue # would close a loop if rank[ru] < rank[rv]: ru, rv = rv, ru # union by rank parent[rv] = ru rank[ru] += rank[ru] == rank[rv] tree.append((w, u, v)) if len(tree) == n - 1: break return tree def prim(n, adj, s=0): # adj[u]: [(v, w), ...] in_tree, tree, pq = [False] * n, [], [(0, s, -1)] while pq: k, u, p = heapq.heappop(pq) if in_tree[u]: continue # old entry (lazy decrease-key) in_tree[u] = True if p >= 0: tree.append((k, p, u)) for v, w in adj[u]: if not in_tree[v]: heapq.heappush(pq, (w, v, u)) # key = one cable, not a sum return tree E = [(4,0,1),(2,0,2),(5,1,2),(3,1,3),(6,2,3),(9,1,4),(7,3,4),(1,3,5),(8,2,5),(10,4,5)] adj = [[] for _ in range(6)] for w, u, v in E: adj[u].append((v, w)); adj[v].append((u, w)) print(sum(t[0] for t in kruskal(6, E)), sum(t[0] for t in prim(6, adj))) # 17 17
MST is the standard proof case for greedy algorithms. The cut property is its greedy-choice property, and its proof is the exchange argument of CLRS 16. Faster methods exist. Karger, Klein and Tarjan (1995) find an MST in expected linear time with random sampling. Chazelle (2000) comes within an inverse-Ackermann factor of linear without randomness. Whether a deterministic linear-time method exists is still open.
Now press Present or Teach. Prove the cut property from memory with the swap 18 − 5 + 4 = 17, then trace Kruskal and Prim on the six towns. Then go back to the hero, press Cheapest five, and say which cable breaks it.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 23, Minimum Spanning Trees (third edition numbering), with Section 35.2 for the tour. The spacing result follows J. Kleinberg and É. Tardos, Algorithm Design, Section 4.7. The towns, prices, devices and step counts on this page are our own.