Minimum Spanning Trees
How Kruskal's and Prim's algorithms connect every node of a weighted graph at the lowest total cost, and what interviewers ask about them.
On this page
A minimum spanning tree (MST) of a weighted, undirected graph is a set of edges that connects every node and has the smallest possible total weight. It solves the problem of connecting a set of places, such as villages that need cable, with the least total cost, when only some pairs can be linked directly. You reach for it when a problem asks for the cheapest way to make everything connected, and the cost you care about is the sum over all the edges you build.
Kruskal's and Prim's algorithms both build the tree greedily, one cheap edge at a time, and both are proven to give a cheapest possible tree.
Why the answer is always a tree
Suppose a plan connects all the nodes and contains a loop. Remove the most expensive edge on the loop. Every node is still connected, because the rest of the loop goes around the gap, and the total cost has dropped. So the cheapest plan never contains a loop, which means it is a tree. A tree on V nodes always has exactly V − 1 edges, so a graph of six villages needs five cables.
A tree that reaches every node is called a spanning tree, and the cheapest one is the minimum spanning tree. The example graph used below has six villages, A to F, and nine possible cables, each with a cost.
Why the cheapest crossing edge is safe
Both algorithms rest on one fact. Split the nodes into any two groups. At least one edge must cross between the groups, or the graph could not be connected. The cheapest edge that crosses the split is always part of some minimum spanning tree.
The reason is an exchange argument. Take a minimum spanning tree that does not contain the cheapest crossing edge, and add that edge to it. The result has a loop, and the loop must cross the split a second time through another edge that costs at least as much. Remove that other edge, and you have a spanning tree that is no more expensive and does contain the cheap edge. So taking the cheapest crossing edge never rules out an optimal answer, and you can build the tree one cheap edge at a time.
Kruskal's algorithm
Kruskal's algorithm sorts all the edges by cost and goes through them from cheapest to most expensive. It takes an edge if its two ends are not yet connected, and skips it if they are, because it would close a loop. It stops when it has V − 1 edges.
The question "are these two nodes already connected?" has to be answered quickly while groups keep merging. Union-find does that: union(u, v) merges the groups of u and v, and returns false if they already shared a root, which is the signal to skip the edge.
sort cables by costfor each cable (u, v) in that order: if find(u) == find(v): skip (would close a loop) else: union(u, v), take the cable stop when you have V − 1 cables- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 0
- groups
- {A} {B} {C} {D} {E} {F}
1Sort the cables by cost. Every village starts in a group of its own.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 1
- groups
- {A} {B} {C} {D} {E,F}
2E–F costs 1. E and F are in different groups, so take it.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 3
- groups
- {A} {B,C} {D} {E,F}
3B–C costs 2. B and C are in different groups, so take it.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 6
- groups
- {A,B,C} {D} {E,F}
4A–C costs 3. A is alone and C is in the group with B, so take it. A, B and C are now one group.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 6
- groups
- {A,B,C} {D} {E,F}
5A–B costs 4.
find(A)andfind(B)return the same root, because A and B are already connected through C. Skip it, since taking it would close a loop. - cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 11
- groups
- {A,B,C,D} {E,F}
6B–D costs 5. D is in a group by itself, so take it.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 11
- groups
- {A,B,C,D} {E,F}
7C–D costs 6. C and D are already in the same group, so skip it.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 18
- groups
- {A,B,C,D,E,F}
8D–E costs 7. It joins the group {A, B, C, D} to the group {E, F}. That makes 5 cables for 6 villages, so the tree is complete and Kruskal stops.
- cables, cheapest first0E–F 11B–C 22A–C 33A–B 44B–D 55C–D 66D–E 77C–E 88D–F 9
- total
- 18
- groups
- {A,B,C,D,E,F}
9The total is 1 + 2 + 3 + 5 + 7 = 18. Kruskal never looked at C–E or D–F, and it skipped two cables, A–B and C–D.
// n villages numbered 0..n-1. edges: list of [cost, u, v].
// UnionFind: the class from the union-find lesson.
function kruskal(n, edges) {
const sorted = [...edges].sort((a, b) => a[0] - b[0]); // cheapest first
const uf = new UnionFind(n);
const chosen = [];
let total = 0;
for (const [cost, u, v] of sorted) {
if (uf.union(u, v)) { // false means u and v were already connected
chosen.push([u, v, cost]);
total += cost;
if (chosen.length === n - 1) break; // a spanning tree has n - 1 edges
}
}
return chosen.length === n - 1 ? { total, chosen } : null; // null: not connected
}# n villages numbered 0..n-1. edges: list of (cost, u, v).
# UnionFind: the class from the union-find lesson.
def kruskal(n, edges):
uf = UnionFind(n)
chosen = []
total = 0
for cost, u, v in sorted(edges): # cheapest first
if uf.union(u, v): # False means u and v were already connected
chosen.append((u, v, cost))
total += cost
if len(chosen) == n - 1: # a spanning tree has n - 1 edges
break
return (total, chosen) if len(chosen) == n - 1 else None # None: not connectedPrim's algorithm
Prim's algorithm grows a single tree from a starting node. At each step it adds the cheapest edge that leaves the tree and reaches a node outside it. That edge is the cheapest one crossing the split between the nodes in the tree and the nodes not yet in it, so it is safe.
A min-heap holds the candidate edges, in the same way as in Dijkstra's algorithm. An edge can become useless after it is pushed, because its far end joined the tree through a cheaper edge. When such an edge is popped, the algorithm skips it.
add start to the tree; push its cableswhile the tree is missing villages: pop the cheapest cable (cost, v) if v is already in the tree: skip add v to the tree; total += cost push v's cables to villages not in the tree- heap (cost, cable)03 A–C14 A–B
- total
- 0
- in tree
- 1
1Start at A. Any village works as the start. Push A's two cables, A–C with cost 3 and A–B with cost 4, onto the heap.
- heap (cost, cable)02 C–B14 A–B26 C–D38 C–E
- total
- 3
- in tree
- 2
2Pop A–C 3 and add C to the tree. Push C's cables to villages outside the tree: C–B 2, C–D 6 and C–E 8.
- heap (cost, cable)04 A–B15 B–D26 C–D38 C–E
- total
- 5
- in tree
- 3
3Pop C–B 2 and add B to the tree. Push B–D 5. B–A is not pushed, because A is already in the tree.
- heap (cost, cable)05 B–D16 C–D28 C–E
- total
- 5
- in tree
- 3
4Pop A–B 4. B is already in the tree, so skip it.
- heap (cost, cable)06 C–D17 D–E28 C–E39 D–F
- total
- 10
- in tree
- 4
5Pop B–D 5 and add D to the tree. Push D–E 7 and D–F 9.
- heap (cost, cable)07 D–E18 C–E29 D–F
- total
- 10
- in tree
- 4
6Pop C–D 6. D is already in the tree, so skip it.
- heap (cost, cable)01 E–F18 C–E29 D–F
- total
- 17
- in tree
- 5
7Pop D–E 7 and add E to the tree. Push E–F 1. This is the cheapest cable on the map, but Prim can only use it once E is in the tree.
- heap (cost, cable)08 C–E19 D–F
- total
- 18
- in tree
- 6
8Pop E–F 1 and add F to the tree. All 6 villages are in the tree. The total is 3 + 2 + 5 + 7 + 1 = 18, the same cost as Kruskal's tree.
// graph: adjacency list, graph[u] = list of [v, cost]. Villages 0..n-1.
// heapPush / heapPop: the pair heap used in the Dijkstra lesson.
function prim(graph, start = 0) {
const inTree = new Set();
const heap = [[0, start]]; // [cost of the cable that reaches node, node]
let total = 0;
while (heap.length > 0 && inTree.size < graph.length) {
const [cost, node] = heapPop(heap);
if (inTree.has(node)) continue; // already joined by a cheaper cable
inTree.add(node);
total += cost;
for (const [next, cableCost] of graph[node]) {
if (!inTree.has(next)) heapPush(heap, [cableCost, next]);
}
}
return inTree.size === graph.length ? total : null; // null: not connected
}import heapq
# graph: adjacency list, graph[u] = list of (v, cost). Villages 0..n-1.
def prim(graph, start=0):
in_tree = set()
heap = [(0, start)] # (cost of the cable that reaches node, node)
total = 0
while heap and len(in_tree) < len(graph):
cost, node = heapq.heappop(heap)
if node in in_tree:
continue # already joined by a cheaper cable
in_tree.add(node)
total += cost
for nxt, cable_cost in graph[node]:
if nxt not in in_tree:
heapq.heappush(heap, (cable_cost, nxt))
return total if len(in_tree) == len(graph) else None # None: not connectedCompared with Dijkstra's code, only the number pushed onto the heap changes. Dijkstra pushes the distance of the whole trip from the start, which is the distance so far plus the edge cost. Prim pushes only the cost of the single edge, because it does not care how far the node is from the start.
Cost of each algorithm
| Approach | Time | Space | Why |
|---|---|---|---|
| Kruskal | O(E log E) | O(V + E) | Sorting the edges dominates. The union-find operations cost almost O(1) per edge. |
| Prim (binary heap) | O(E log V) | O(V + E) | Each edge can cause one heap push, and each push or pop costs O(log E), which is O(log V). |
Variants and when each applies
Kruskal or Prim
Both give a tree of the same total cost. Kruskal works on a plain list of edges and needs a union-find structure, so it is the natural choice when the input is an edge list. Prim works on an adjacency list and needs a heap, so it fits when you already have the graph in that form. On a sparse graph their running times are similar.
Dense graphs
When every pair of nodes has an edge, as in "connect these points on a plane where the cost is the distance", E is about V². Kruskal then sorts about V² edges, which costs O(V² log V). Prim can drop the heap and keep an array that stores, for each node outside the tree, the cheapest edge found so far to the tree. Each step scans the array for the smallest entry, so the whole run is O(V²). This is the better choice for dense inputs.
Equal edge weights
If several edges have the same cost, more than one minimum spanning tree can exist, and different tie-breaking gives different trees. All of them have the same total cost. If every edge weight is distinct, the minimum spanning tree is unique. A problem that asks for the exact edges therefore needs a stated rule for ties.
Maximum spanning tree and negative weights
To find the most expensive spanning tree, sort the edges from most to least expensive in Kruskal's algorithm, or negate every weight and run the normal version. Negative weights need no special handling, because both algorithms only compare edge costs, unlike Dijkstra's algorithm.
Disconnected graphs
If the graph is in several separate pieces, no spanning tree exists. Kruskal ends with fewer than V − 1 edges, and Prim empties its heap while some nodes are still outside the tree. If the problem allows it, running Kruskal to the end gives a minimum spanning forest, which is one tree for each connected piece.
When it does not apply
A minimum spanning tree does not give shortest routes. It minimises the total cost of all the edges, and a path through the tree between two nodes can be much longer than the best path in the graph. For the cheapest way to get from one node to another, use Dijkstra's algorithm. Both algorithms also assume undirected edges. The directed version, which finds the cheapest set of arrows that lets one root reach every node, is a different problem with its own algorithm.
In the example, the path from A to F inside the tree is A–C–B–D–E–F and costs 18, while the cheapest route in the whole graph is A–C–E–F at 3 + 8 + 1 = 12.
Edges that no longer help
Both algorithms need a guard against edges that no longer help. Kruskal skips an edge whose ends already share a root. Prim skips a popped edge whose node is already in the tree; without that check it would add the node twice, count its cost twice, and could form a loop.
In the interview
Look for a problem that asks for the minimum total cost, length or weight needed to connect all of a set of items, where an edge can be built between certain pairs. Typical wordings are connecting cities with roads or pipes, or wiring computers together. If the problem instead asks about the cost of one route from a start to a target, it is a shortest-path problem.
Questions to expect:
- "Why is picking the cheapest edge correct?" State the cut property: for any split of the nodes into two groups, the cheapest edge crossing the split belongs to some minimum spanning tree. Then describe the exchange argument: swapping a more expensive crossing edge for the cheaper one never increases the cost.
- "Kruskal or Prim, and why?" Say that both are correct, and choose by input and density. Kruskal fits an edge list and sparse graphs, and Prim with an array fits dense graphs in O(V²).
- "What is the complexity?" Kruskal is O(E log E) because of the sort, which is the same as O(E log V). Prim with a binary heap is O(E log V).
- "Why use union-find in Kruskal instead of a graph search to detect loops?" A search from u to see whether v is reachable costs O(V + E) per edge, which makes the whole algorithm O(E · (V + E)). Union-find with path compression and union by size answers the same question in almost constant time, so the sort stays the dominant cost.
- "How do you check whether a given edge belongs to some minimum spanning tree?" Look for a path between its two ends that uses only edges strictly cheaper than it. If such a path exists, the edge would close a loop whose most expensive edge it is, so it can be left out. If no such path exists, some minimum spanning tree contains it.
- "Is the minimum spanning tree unique?" Only if all the edge weights are different. With ties, several trees can have the same minimum total, and the algorithms may return different ones.
- "What if the graph is not connected?" No spanning tree exists. Detect it by counting the edges or nodes taken, and either report that the nodes cannot all be connected or return a spanning forest, depending on what the problem asks.
A connected graph has 10 nodes and 25 edges. How many edges does its minimum spanning tree have?
Kruskal reaches the edge D–G, and find(D) and find(G) return the same root. What should it do?
Prim's algorithm and Dijkstra's algorithm both pop from a min-heap. What does Prim push for a neighbour of the node it just added?
What to practise next
Kruskal's and Prim's algorithms are both greedy: each takes the cheapest safe edge and never reconsiders it. Greedy algorithms covers how to tell when that approach is correct and how to recognise when it is not.