Minimum Spanning Trees: Kruskal's and Prim's Algorithms
You need to connect a set of sites with cable, and each possible link has a cost. Which links should you build so that every site is connected and the total cost is as small as possible? The answer is a minimum spanning tree (MST), and two short greedy algorithms find one: Kruskal's and Prim's. This guide defines the problem carefully, explains why greed works here (it does not always, as greedy versus dynamic programming shows), and runs both algorithms on the same graph. Examples use Python 3.10 or later and only the standard library.
Spanning trees and the minimum one
Take a connected, undirected, weighted graph with V vertices. A spanning tree is a subset of its edges that connects all V vertices and contains no cycle. Every spanning tree has exactly V - 1 edges: fewer cannot connect V vertices, and one more would close a cycle. A minimum spanning tree is a spanning tree whose total edge weight is as small as possible.
An MST minimizes the sum of all its edges. It does not minimize the distance between any particular pair of vertices, and it is not the same thing as a shortest-path tree. A triangle shows the difference. Let A-B and B-C weigh 2 and A-C weigh 3. The MST is A-B plus B-C, total 4. But inside that tree the route from A to C costs 2 + 2 = 4, while the direct edge costs 3. The shortest-path tree from A (what Dijkstra's algorithm builds) is A-B plus A-C, total 5: better for travelers starting at A, worse for whoever pays for the cable.
If the graph is not connected, no spanning tree exists. The natural answer is then a minimum spanning forest: one minimum spanning tree per connected component.
The cut property
Both algorithms rest on one fact. Split the vertices into any two nonempty groups; the edges with one end in each group are said to cross the cut. Then:
The lightest edge crossing any cut belongs to some minimum spanning tree. (If it is strictly lighter than every other crossing edge, it belongs to every MST.)
In plain words: any spanning tree must use at least one edge across the cut to join the two groups. Suppose a tree uses a heavier crossing edge instead of the lightest one. Add the lightest edge; that makes a cycle, and the cycle crosses the cut a second time through some other crossing edge. Remove that other edge. The result is still a spanning tree, and it weighs no more than before. So choosing the lightest crossing edge never hurts.
This is the greedy-choice property for MSTs, and it is why taking the cheapest safe edge, again and again, gives an optimal tree.
The example graph
Six vertices, A to F, and nine weighted edges: A-B 4, A-C 1, B-C 2, B-D 5, C-D 8, C-E 10, D-E 2, D-F 6, E-F 3. The program builds both trees and prints them.
import heapq
edges = [
("A", "B", 4), ("A", "C", 1), ("B", "C", 2), ("B", "D", 5),
("C", "D", 8), ("C", "E", 10), ("D", "E", 2), ("D", "F", 6),
("E", "F", 3),
]
vertices = sorted({x for u, v, _ in edges for x in (u, v)})
class UnionFind:
def __init__(self, items):
self.parent = {x: x for x in items}
self.rank = {x: 0 for x in items}
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root: # path compression
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # same component: would form a cycle
if self.rank[ra] < self.rank[rb]: # union by rank
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def kruskal(vertices, edges):
uf = UnionFind(vertices)
tree = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
if uf.union(u, v):
tree.append((u, v, w))
return tree
def prim(vertices, edges, start):
adj = {v: [] for v in vertices}
for u, v, w in edges:
adj[u].append((w, u, v))
adj[v].append((w, v, u))
in_tree = {start}
heap = list(adj[start])
heapq.heapify(heap)
tree = []
while heap and len(in_tree) < len(vertices):
w, u, v = heapq.heappop(heap)
if v in in_tree:
continue # stale: both ends already in the tree
in_tree.add(v)
tree.append((u, v, w))
for edge in adj[v]:
if edge[2] not in in_tree:
heapq.heappush(heap, edge)
return tree
k = kruskal(vertices, edges)
p = prim(vertices, edges, "A")
print("Kruskal:", k, "total", sum(w for _, _, w in k))
print("Prim: ", p, "total", sum(w for _, _, w in p))
Kruskal: [('A', 'C', 1), ('B', 'C', 2), ('D', 'E', 2), ('E', 'F', 3), ('B', 'D', 5)] total 13
Prim: [('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 5), ('D', 'E', 2), ('E', 'F', 3)] total 13
Kruskal's algorithm
Kruskal's algorithm looks at edges from lightest to heaviest and keeps an edge if it joins two different components of the tree built so far; otherwise the edge would close a cycle, and it is skipped. On the example: A-C (1), B-C (2) and D-E (2) are kept, E-F (3) is kept, A-B (4) is skipped because A and B are already connected through C, and B-D (5) is kept, joining the two halves. That is V - 1 = 5 edges, so the tree is done, with total weight 13. Each kept edge is the lightest edge across the cut between its component and the rest, so the cut property says it is safe.
The "are these two already connected?" test is where the data structure matters. A union-find (disjoint-set) structure keeps one representative per component. find follows parent links to the representative, and union links two representatives. Two standard improvements keep the trees inside it flat:
- path compression: after a
find, point every vertex on the path straight at the root; - union by rank: attach the shorter tree under the taller one.
With both, a sequence of operations costs nearly constant amortized time per operation, so sorting dominates. Kruskal's algorithm runs in O(E log E) time. Since E is less than V^2, log E is less than 2 log V, so this is the same as O(E log V).
Prim's algorithm
Prim's algorithm grows a single tree from a start vertex. At each step it adds the lightest edge that connects a tree vertex to a vertex outside the tree, which is the lightest edge across the cut between "in the tree" and "not yet", so again the cut property makes it safe.
A min-heap of candidate edges makes "the lightest edge leaving the tree" fast. As in Dijkstra's algorithm with heapq, the code uses lazy deletion: edges whose far end has already joined the tree are skipped when popped. From A: A-C (1), then C-B (2), then B-D (5), since the cheaper A-B (4) now leads inside the tree, then D-E (2) and E-F (3). The total is 13 again.
Running time depends on the priority queue:
- with a binary heap, each edge is pushed and popped at most twice, giving O(E log V);
- with a plain array of the cheapest known connection costs, scanned for the minimum at each step, it is O(V^2), which is better for dense graphs;
- more advanced heaps lower the bound to O(E + V log V) in theory.
Prim's algorithm and Dijkstra's look alike, and the difference is one line. Dijkstra's algorithm orders vertices by total distance from the source; Prim's orders them by the weight of the single edge that would connect them to the tree.
Same total, maybe different trees
Both algorithms always produce a minimum spanning tree, so the total weight is always the same. The trees themselves can differ when edges tie. If all edge weights are distinct, the MST is unique and both algorithms return the same edges. Here the two lists contain the same five edges in different orders (Prim's printed C-B for B-C because it reached B from C).
| Kruskal | Prim (binary heap) | |
|---|---|---|
| Grows | A forest that merges into one tree | One tree from a start vertex |
| Key structure | Union-find | Priority queue |
| Time | O(E log E) | O(E log V); O(V^2) with an array |
| Disconnected graph | Gives a minimum spanning forest | Spans only the start vertex's component |
| Good fit | Sparse graphs, edges given as a list | Dense graphs (array version), adjacency lists |
Where MSTs are used
- Network design: cabling, piping or road layouts where every site must be connected at least total cost.
- Clustering: build the MST of points with distances as weights, then delete the k - 1 heaviest edges; the remaining pieces are k clusters.
- A building block: some approximation algorithms for hard routing problems start from an MST.
History
Joseph Kruskal published his algorithm in 1956 ("On the shortest spanning subtree of a graph and the traveling salesman problem", Proceedings of the American Mathematical Society). Robert Prim published his in 1957 ("Shortest connection networks and some generalizations", Bell System Technical Journal). Prim's method had already been described by Vojtěch Jarník in 1930, which is why it is sometimes called the Jarník or Prim-Jarník algorithm, and Dijkstra gave it again in his 1959 paper.
Check yourself
- A connected graph has 10 vertices and 30 edges. How many edges are in its MST? (9.)
- Kruskal's algorithm considers an edge whose ends are already in the same component. Why skip it? (Adding it would close a cycle, and every edge already in the tree weighs no more than it.)
- Does adding the same constant to every edge weight change which tree is minimum? (No. Every spanning tree has V - 1 edges, so every total rises by the same amount. Compare shortest paths, where it does change the answer.)