The problem
You have a set of sites and the cost of every possible direct link between two of them: cables between buildings, pipes between tanks, roads between villages. You want every site connected, directly or through others, at the lowest total cost. Redundant links are wasted money, so the answer never contains a cycle.
In graph terms: given a connected, undirected graph with weighted edges, a spanning tree is a
subset of edges that connects all n nodes and has no cycle. A minimum spanning tree (MST) is a
spanning tree whose total weight is as small as possible.
Three facts about trees are used throughout:
- A tree on
nnodes has exactly n − 1 edges. Fewer cannot connect everything; one more always closes a cycle. - Adding any edge to a spanning tree creates exactly one cycle.
- Removing any edge of a tree splits it into exactly two components.
If the graph is disconnected, no spanning tree exists. The natural answer is then a minimum
spanning forest: one minimum spanning tree per connected component, n − c edges for c
components. Kruskal produces it without any change.
This module comes after union-find on purpose: Kruskal's algorithm is the classic use of that structure, and the lab below reuses the exact same union-find (union by rank, path compression).
Two properties that make greedy safe
Both MST algorithms in this lesson are greedy: they commit to an edge and never take it back.
That is only correct because of two properties. A cut is a split of the nodes into two non-empty
groups S and V \ S; an edge crosses the cut if it has one endpoint on each side.
Cut property. For any cut, a minimum-weight edge crossing it belongs to some minimum spanning tree. If it is the only lightest crossing edge, it belongs to every MST.
Why. Take an MST T that does not contain the light crossing edge e = (u, v). Adding e to T
closes a cycle. That cycle goes from u's side to v's side through e and must come back across
the cut somewhere else, through some tree edge f. Swap them: T − f + e is still a spanning tree,
and since w(e) ≤ w(f) its weight is no larger. So an MST with e exists.
Cycle property. For any cycle, a maximum-weight edge on it can be left out: some MST avoids it. If it is the only heaviest edge on the cycle, no MST contains it.
Why. If an MST T contains the heavy edge f, removing f splits T into two parts. The rest of
the cycle connects those parts again, so some other cycle edge e crosses between them. T − f + e
is a spanning tree, and w(e) ≤ w(f), so it is no heavier.
Both arguments are exchange arguments: swap one edge for another and show the result is no worse. The same technique proves the greedy interval-scheduling rule in the Greedy module.
Kruskal's algorithm
Kruskal looks at edges from lightest to heaviest and keeps an edge unless it would close a cycle:
sort edges by weight (ties: input order)
make every node its own set # union-find
tree = []
for each edge (u, v, w) in sorted order:
if tree has n − 1 edges: stop # nothing more can be added
if find(u) == find(v): reject # already connected → would close a cycle
else: union(u, v); tree.append(edge)
Union-find answers "are u and v already connected by chosen edges?" in near-constant time, which
is exactly the question the loop asks. The lab shows the graph with each edge's weight, the sorted
list in front in scan order, and a second lane holding the tree as it grows. Each node is tagged with
its union-find root, so nodes with the same tag are already in one component.
Why every decision is correct
- Accept. When
(u, v)is accepted,uandvare in different components. LetAbeu's component, and cut the graph intoAand everything else. Every lighter edge crossing this cut has already been examined, and it would have been accepted (its endpoints were in different components), which would have madeAlarger. So no lighter edge crosses the cut:(u, v)is a lightest crossing edge, and the cut property says it is safe. - Reject. When
(u, v)is rejected, chosen edges already connectuandv, so(u, v)closes a cycle with them. Every chosen edge was examined earlier and is at most as heavy, so(u, v)is a heaviest edge on that cycle, and the cycle property says some MST does without it.
A worked trace
The lab's Seven nodes, cycles rejected preset has eleven edges. Sorted by weight (ties in input
order): 0–3:5, 2–4:5, 3–5:6, 0–1:7, 1–4:7, 1–2:8, 4–5:8, 1–3:9, 4–6:9, 5–6:11, 3–4:15.
| Step | Edge | Roots | Decision | Tree weight |
|---|---|---|---|---|
| 1 | 0–3 (5) | different | accept | 5 |
| 2 | 2–4 (5) | different | accept | 10 |
| 3 | 3–5 (6) | different | accept | 16 |
| 4 | 0–1 (7) | different | accept | 23 |
| 5 | 1–4 (7) | different | accept: joins {0, 1, 3, 5} and {2, 4} | 30 |
| 6 | 1–2 (8) | same | reject: cycle 1–4–2–1 | 30 |
| 7 | 4–5 (8) | same | reject: cycle 4–1–0–3–5–4 | 30 |
| 8 | 1–3 (9) | same | reject: cycle 1–0–3–1 | 30 |
| 9 | 4–6 (9) | different | accept: 6 edges, done | 39 |
After step 9 the tree has n − 1 = 6 edges, so 5–6 and 3–4 are never examined: the lab fades
them and its Edges examined metric stops at 9. The total, 39, is what the shared fixture records
for all four languages.
Ties, negative weights and uniqueness
- Ties. When several edges share a weight, more than one MST can exist. They all have the same total weight; only the edge set differs. This lab breaks ties by input order (the Equal weights preset), and so do the four implementations, which is why one fixture can pin the exact edges.
- Distinct weights mean a unique MST. With no ties, every accepted edge was the only lightest edge across its cut, so it is in every MST.
- Negative weights are fine. Both properties only compare weights; nothing adds them along a path. The Negative weights preset takes the −3 edge first. (Contrast Dijkstra, which breaks with negative edges.) A maximum spanning tree is the same algorithm with the order reversed, or with every weight negated.
Prim's algorithm
Prim grows a single tree from a start node. At every step it adds the lightest edge leaving the tree, which is the cut property applied to the cut (tree, rest). With a binary heap and lazy deletion, the same trick the Dijkstra lesson uses:
inTree[*] = false
push every edge of the start node onto a min-heap keyed by weight
inTree[start] = true
while the heap is not empty and the tree has fewer than n − 1 edges:
(w, u, v) = pop the lightest edge # u is in the tree
if inTree[v]: continue # stale: both ends already in the tree
inTree[v] = true; add (u, v) to the tree
push every edge (v, x) with inTree[x] = false
Prim never needs union-find: "is v already in the tree?" is a boolean per node, because there is only
one tree. On a disconnected graph it spans only the start node's component; run it again from an
unvisited node to build a forest.
This lesson's lab and code cover Kruskal only. Prim's heap mechanics (push, pop, stale entries) are the ones you can step through in the Dijkstra lab; the difference is the key: Prim orders the heap by the weight of the single edge into the tree, Dijkstra by the total distance from the source.
Complexity
V nodes, E edges, adjacency lists.
| Algorithm | Time | Extra space | Best when |
|---|---|---|---|
| Kruskal (sort + union-find) | O(E log E) = O(E log V) | O(V + E): union-find arrays, sorted order | sparse graphs, edges already in a list, or already sorted |
| Prim, binary heap, lazy deletion | O(E log V) | O(V + E): flags plus up to E heap entries | sparse graphs given as adjacency lists |
| Prim, array of best edge weights, no heap | O(V²) | O(V) | dense graphs, adjacency matrix |
- Kruskal: sorting costs O(E log E); since E ≤ V², log E ≤ 2 log V, so that is O(E log V). The loop makes at most 2E finds and V − 1 unions, O(E α(V)) with union by rank and path compression, which the sort dominates. If the edges arrive already sorted (or the weights are small integers you can counting-sort), the union-find part is all that remains.
- The early stop after n − 1 accepted edges saves work in practice but not in the worst case: the heaviest edge may be the one that completes the tree.
- On a dense graph (E close to V²), the O(V²) array version of Prim beats both O(E log V) = O(V² log V) versions.
Minimum spanning tree versus shortest-path tree
They are easy to confuse because both are trees chosen by weight. Take a triangle with edges 0–1:2,
1–2:2 and 0–2:3. The MST is {0–1, 1–2} with weight 4. The shortest-path tree from node 0 is
{0–1, 0–2}, because the direct edge reaches 2 at cost 3 instead of 4. The MST minimises the sum of
the chosen edges; a shortest-path tree minimises each node's distance from one source. Neither
answers the other's question.
The teaching implementation
Kruskal.Run / kruskal sorts edge indices by (weight, index), then runs the loop above on the
UnionFind class from the union-find lesson; it returns the accepted edge indices, the total weight,
the number of components (1 for a spanning tree) and how many edges were examined. The listings are
the files the tests run. Each language reads the shared fixture (forests, ties, negative weights,
isolated nodes, an expensive bridge that must be taken) and compares the total weight with a brute
force over every subset of edges on 500 random small graphs, checking that the result is acyclic
and has one tree per component. Brute force is hopeless beyond about 20 edges, but it shares no logic
with Kruskal, which makes it an honest check.
Language notes
None of the four standard libraries ships a union-find or an MST routine, so the code builds on the union-find lesson's class. What differs is sorting, and whether the sort keeps ties in order.
| Language | Sort used | Notes |
|---|---|---|
| C# | Array.Sort(int[], Comparison<int>) |
Introsort: not stable, so the comparison breaks ties by index explicitly. LINQ OrderBy(...).ThenBy(...) is stable but allocates. For Prim, PriorityQueue<TElement, TPriority> is a min-heap without decrease-key. |
| Python | sorted(range(m), key=lambda i: (w[i], i)) |
Timsort is stable, so key=lambda i: w[i] alone would already keep ties in input order; the tuple makes the rule explicit. heapq provides the min-heap for Prim. |
| Java | Arrays.sort(Integer[], Comparator) |
For object arrays the sort is documented as stable (a merge sort); for int[] it is a dual-pivot quicksort and not stable, which is why indices are boxed here. PriorityQueue with a comparator for Prim. |
| C++ | std::ranges::sort |
Not stable; the comparator breaks ties by index. std::ranges::stable_sort would also work. std::priority_queue is a max-heap unless you pass std::greater<>. |
Totals are accumulated in 64-bit integers (long / long long; Python integers do not overflow): a
tree with many heavy edges can exceed the range of a 32-bit sum even when every single weight fits.
Common mistakes
- Checking for cycles with a fresh DFS for every edge. It works, but costs O(V) per edge and O(E·V) overall. Union-find makes the same test nearly O(1).
- Running it on a directed graph. MSTs are defined for undirected graphs. The directed analogue, a minimum spanning arborescence, needs a different algorithm (Chu–Liu/Edmonds).
- Expecting a spanning tree from a disconnected graph. Check that the result has
n − 1edges (or that one component remains) before treating it as a tree. - Sorting with an unstable sort and expecting a particular tree. The weight is always minimal, but which of several equal-weight trees you get depends on tie-breaking.
- Mixing up Prim and Dijkstra keys: Prim's key is the weight of one edge, not a path length.
Edge cases
- One node and no edges: the empty tree, weight 0.
- Isolated nodes: each one is its own component in the forest.
- A single expensive bridge between two groups is in every spanning tree; Kruskal reaches it last.
- Parallel edges: only the cheaper copy can be chosen; the lab accepts one edge per pair so it can draw them, and rejects self-loops (a loop is a one-edge cycle). The implementations tolerate both.
Worked practice
1. In the seven-node trace, why is 4–5 (weight 8) rejected while 4–6 (weight 9) is accepted?
Answer
When 4–5 comes up, nodes 4 and 5 are already connected through 4–1–0–3–5, so their union-find roots match and the edge would close a cycle (the cycle property: it is the heaviest edge on it). Node 6 has no chosen edge yet when 4–6 comes up, so the roots differ: 4–6 is the lightest edge crossing the cut between {6} and the rest, and the cut property makes it safe.
2. A connected graph has 50 nodes and 1,200 edges. How many edges does every MST have, and how many edges does Kruskal examine at least?
Answer
Every spanning tree has 49 edges. Kruskal examines at least 49 (if the 49 lightest edges happen to be acyclic) and at most all 1,200 (if the edge that completes the tree is the heaviest of all).
3. All edge weights in a connected graph are different. Can two different MSTs exist?
Answer
No. Each edge Kruskal accepts is the unique lightest edge across a cut, and by the strict form of the cut property such an edge is in every MST. All n − 1 accepted edges are therefore in every MST, and an MST has only n − 1 edges.
4. You have 2,000 nodes and nearly every pair is connected (about 2 million edges). Kruskal, heap Prim or array Prim?
Answer
Array Prim: O(V²) = 4 million basic steps. Kruskal sorts 2 million edges, about 2·10⁶ · 21 ≈ 42 million comparisons, and heap Prim is in the same range. On a dense graph the heap's logarithm costs more than it saves.
5. Your colleague computes an MST of a road network and uses its paths for navigation. What goes wrong?
Answer
The MST minimises the total length of the roads kept, not the length of the path between two places. In the triangle 0–1:2, 1–2:2, 0–2:3 the MST route from 0 to 2 costs 4 while the direct road costs 3. Navigation needs a shortest-path algorithm such as Dijkstra.
Summary
- A minimum spanning tree connects all n nodes with n − 1 edges of least total weight; a disconnected graph gets a minimum spanning forest.
- Cut property: a lightest edge across any cut is safe to add. Cycle property: a heaviest edge on any cycle is safe to drop.
- Kruskal: sort edges, keep each one unless union-find says its endpoints are already connected. O(E log E).
- Prim: grow one tree, always adding the lightest edge leaving it, with a heap (O(E log V)) or an array (O(V²), better for dense graphs).
- Ties allow several MSTs of equal weight; negative weights are fine; an MST is not a shortest-path tree.