Minimum spanning trees: Kruskal & Prim
Build a minimum spanning tree with Kruskal's and Prim's algorithms.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
A minimum spanning tree connects every vertex of a weighted undirected graph with the smallest total edge weight and no cycles. Kruskal's algorithm adds the cheapest edges that do not form a cycle, using union-find. Prim's algorithm grows one tree outward by always taking the cheapest edge leaving it.
Explained simply
Imagine you must connect five villages with water pipes. Every possible pipe has a price. You do not need a pipe between every pair, only enough so water can reach every village somehow. Which pipes should you build to spend the least? The answer is a minimum spanning tree, or MST.
Spanning means it touches every vertex. Tree means it has no loops, because a loop would always contain a pipe you could remove and still keep everyone connected. A tree on V vertices always has exactly V - 1 edges.
Two famous algorithms build it. Kruskal's algorithm sorts all edges from cheapest to most expensive and takes each one unless it would close a loop. Prim's algorithm starts at one vertex and keeps adding the cheapest edge that reaches a new vertex.
Both are greedy: they take the cheapest safe edge and never change their mind. Unlike many greedy ideas, this one is provably correct, thanks to a simple rule called the cut property.
Press Play on a diagram to walk through it one step at a time.
- 1Sort edges
Ascending by weight.
- 2Take next edge
Cheapest remaining (u, v).
- 3Cycle check
find(u) != find(v)?
- 4Add and union
Keep edge, merge sets.
- 5Stop
After V-1 edges.
- 1Start at A
Heap: (1, B), (4, C).
- 2Pop (1, B)
Add B, total 1; push (2, C), (5, D).
- 3Pop (2, C)
Add C, total 3; push (3, D).
- 4Pop (3, D)
Add D, total 6.
- 5Done
4 vertices, 3 edges; (4, C) and (5, D) are stale.
- Edges A-B and B-C
- Total weight 4
- A to C costs 4 inside it
- Edges A-B and A-C
- Total weight 5
- A to C costs 3 inside it
In depth
The cut property, and why greedy is safe here
Split the vertices into any two groups. That split is called a cut. The edges with one end in each group cross the cut. The cut property says: the cheapest crossing edge belongs to some MST.
Why? Take any MST that does not use that cheapest edge e. Add e to it, and you create exactly one loop. That loop must cross the cut a second time, through some other edge f that costs at least as much as e. Remove f. You still have a spanning tree, and it costs no more. So a best tree with e exists. This swap is an exchange argument.
Kruskal and Prim are just two ways of picking cuts. Prim's cut is "tree so far versus the rest". Kruskal's cut is "one component versus everything else" at the moment it adds an edge.
- Cycle property: the strictly heaviest edge on a loop is in no MST
- Distinct weights mean exactly one MST
- Every MST of a graph has the same total weight
Kruskal in detail
Sort the edges by weight, then scan them. For each edge (u, v), ask union-find whether u and v are already in the same component. If not, keep the edge and merge the two components. Stop after V - 1 edges.
Sorting costs O(E log E). Since E is at most V^2, that equals O(E log V). The union-find work is O(E alpha(V)), where alpha is the inverse Ackermann function, which is at most 4 for any input you could ever store. So sorting dominates.
If the graph is not connected, Kruskal never reaches V - 1 edges. What it builds instead is a minimum spanning forest, one tree per component. Checking len(used) == V - 1 tells you whether the graph was connected.
Prim, and choosing by density
Prim keeps a set of vertices already in the tree and a heap of edges leaving it. Pop the cheapest edge. If its far end is already in the tree, skip it (a stale entry). Otherwise add that vertex and push its edges. With heapq and lazy deletion, the heap holds up to E entries and the total is O(E log V).
For a dense graph, where almost every pair has an edge, use the array version instead. Keep best[v], the cheapest edge from the tree to v, and on each step scan all vertices for the smallest one. That is V steps of O(V) work, O(V^2) total, with no heap and no edge list. When E is close to V^2, this beats both Kruskal and heap Prim.
- O(E log E) for the sort
- Needs union-find
- Best with an edge list
- Builds a forest if disconnected
- O(E log V)
- Needs adjacency lists
- Grows from one vertex
- O(V^2), no heap
- Best for dense graphs
- Great for all-pairs point distances
MST is not a shortest-path tree
A common mix-up: the MST minimises the total cost of the whole network, not the distance from one vertex to another. Take a triangle with A to B 2, B to C 2 and A to C 3. The MST uses A-B and B-C, total 4. But the shortest path from A to C is the direct edge 3, while the MST route from A to C costs 4.
Other facts worth knowing: MST algorithms work with negative weights, because only the order of weights matters. A maximum spanning tree is found by sorting in descending order. The MST also minimises the largest edge used (a minimum bottleneck tree), which is useful for questions like "the lowest bridge height you must pass".
Real uses
Designing cheap networks is the obvious use: cables, roads, pipes, circuit wiring. A less obvious one is clustering. Run Kruskal but stop when k components remain. The result is k groups, and the gap between groups (the next edge Kruskal would take) is as large as possible. This is called single-linkage clustering.
MSTs also appear inside other algorithms. For the travelling salesperson problem with distances that obey the triangle inequality, walking around an MST and skipping repeated cities gives a tour at most twice the optimal length.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1State the cut property~45m
- 2Implement Kruskal with union-find~45m
- 3Implement Prim with a heap~45m
- 4Choose between them by graph density~45m
Key points
- Kruskal: O(E log E), dominated by sorting.
- Prim with a heap: O(E log V); good for dense graphs.
- Cut property: the lightest edge across any cut belongs to some MST.
- An MST has exactly V-1 edges in a connected graph.
Key terms
Tap a card to flip it. 0/3 known
Examples
def kruskal(n, edges): # edges = [(w, u, v)], O(E log E)
dsu = DSU(n) # from the union-find topic
total, used = 0, []
for w, u, v in sorted(edges):
if dsu.union(u, v):
total += w
used.append((u, v))
return total, used
print(kruskal(4, [(1, 0, 1), (3, 1, 2), (2, 0, 2), (4, 2, 3)]))
# (7, [(0, 1), (0, 2), (2, 3)])Prim with heapq, step by step
We use the graph from the trace diagram. Step 1: put A in the tree and push its edges. Step 2: pop the cheapest edge; if it leads to a new vertex, add it and push that vertex's edges. Step 3: skip popped edges whose end is already inside. Step 4: stop once all vertices are in. Adjacency entries are stored as (weight, vertex) so the heap orders them by weight.
import heapq
def prim(adj, start): # adj[u] = [(w, v)], undirected
seen, total, heap = {start}, 0, list(adj[start])
heapq.heapify(heap)
while heap and len(seen) < len(adj):
w, v = heapq.heappop(heap)
if v in seen: continue # stale: already in the tree
seen.add(v); total += w
for e in adj[v]:
if e[1] not in seen: heapq.heappush(heap, e)
return total
adj = {"A": [(1, "B"), (4, "C")], "B": [(1, "A"), (2, "C"), (5, "D")],
"C": [(4, "A"), (2, "B"), (3, "D")], "D": [(5, "B"), (3, "C")]}
print(prim(adj, "A")) # 6Connect all points (a dense graph)
Given points on a grid, connecting two costs their Manhattan distance |x1 - x2| + |y1 - y2|. Every pair is a possible edge, so with n points there are n(n - 1)/2 edges. Building and sorting them all is wasteful. The array version of Prim never builds the edge list: it keeps best[v] for every point and updates it from each newly added point. Time O(n^2), space O(n). For points (0,0), (2,2), (3,10), (5,2), (7,0) the answer is 20.
def min_cost_connect(points): # O(n^2) Prim, no heap
n = len(points)
best = [float("inf")] * n # cheapest edge into the tree
best[0], in_tree, total = 0, [False] * n, 0
for _ in range(n):
u = min((i for i in range(n) if not in_tree[i]), key=best.__getitem__)
in_tree[u] = True; total += best[u]
x, y = points[u]
for v in range(n):
if not in_tree[v]:
best[v] = min(best[v], abs(x - points[v][0]) + abs(y - points[v][1]))
return total
print(min_cost_connect([[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]])) # 20Quick reference
- An MST of a connected graph with V vertices has exactly V - 1 edges
- Kruskal: sort edges, keep each one whose ends are in different union-find sets; O(E log E)
- Prim with heapq and lazy deletion: O(E log V); array Prim: O(V^2) for dense graphs
- Cut property: the cheapest edge crossing any cut is in some MST
- Distinct weights mean the MST is unique
- Kruskal stopped at k components gives k clusters with the widest gaps
- Negative weights are fine for MST; directed graphs are not (that is a different problem)
- MST minimises the total, not the distance between two vertices
Common mistakes
- Applying MST algorithms to directed graphs.
- Confusing an MST with a shortest-path tree; they differ in general.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Change the explainer's kruskal so it returns None when the graph is not connected, instead of a forest.
- Exercise 2medium
Group n items into exactly k clusters so the smallest distance between two different clusters is as large as possible. edges are (w, u, v). Return that spacing.
- Exercise 3hard
n houses (1 to n). Digging a well at house i costs wells[i - 1]; a pipe [u, v, c] connects two houses for cost c. Find the minimum cost so every house has water.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is the minimum spanning tree unique?
- If all edge weights are different, yes. With equal weights there can be several MSTs, but they all have the same total weight.
- Kruskal or Prim: which should I use?
- Use Kruskal when you already have an edge list or the graph is sparse; it is short to write with union-find. Use array Prim when the graph is dense, such as all pairs of points.
- Can I find an MST of a directed graph with Kruskal or Prim?
- No. The directed version is called a minimum spanning arborescence and needs a different method, the Chu-Liu/Edmonds algorithm.
- Do MST algorithms work with negative edge weights?
- Yes. Kruskal and Prim only compare weights, so negative values cause no problem, unlike in shortest-path algorithms.