Kruskal's algorithm
medium 20 minKruskal's algorithm finds a minimum spanning tree: the cheapest set of edges that connects every vertex with no cycles.
Video lesson · Chapter 1 of 7
Bridge auction
Kruskal's algorithm in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
Sort every edge by weight. One O(E log E) sort puts the cheapest edge first; this is the main cost of the algorithm
Understand it
Start here
What a minimum spanning tree is
Quick recap
Weighted graph
Vertices joined by edges, each with a cost . Basics in graphs intro.
Tree
Connected and acyclic. On vertices it always has exactly edges.
Spanning
It touches every vertex of the graph, using only the graph's own edges.
Minimum
Of all spanning trees, the one whose edge weights add up to the least.
The goal
Picture islands and the bridges you could build between them, each with a price. You want every island reachable from every other for the least money. Any loop of bridges wastes money, since one bridge in the loop could be dropped and everything stays connected. So the answer is a tree, and the cheapest such tree is the minimum spanning tree.
The idea
Cheapest edge first, skip any cycle
Kruskal's algorithm is greedy and edge-centric. It never grows from a start vertex. Instead it keeps a forest of fragments, starting with every vertex alone, and repeatedly takes the cheapest remaining edge. If that edge joins two different fragments, it goes in and the fragments merge. If both ends are already in the same fragment, the edge would close a loop, so it is skipped.
- 1SortAll edges by weight, O(E log E)
- 2Findfind(u) and find(v): which components?
- 3Add or skipDifferent roots: add and union. Same root: skip
- 4Enough?Stop at V - 1 edges
Sort, Add if no cycle, Find components, Edge accepted or rejected: SAFE.
Kruskal's algorithm
Step 1
Sort the edges
The simple graph, sorted
| Order | Edge | Weight | Verdict |
|---|---|---|---|
| 1 | B-C | 1 | accept |
| 2 | E-F | 1 | accept |
| 3 | B-D | 2 | accept |
| 4 | D-E | 2 | accept, merges {B, C, D} with {E, F} |
| 5 | A-C | 3 | accept, 5 = V - 1 edges: stop |
| 6 to 9 | A-B, C-D, C-E, D-F | 4, 4, 5, 6 | never examined |
Sorting is the bottleneck
sorted(edges, key=lambda e: e[2]) is a stable sort. Everything after it is nearly linear, so the sort sets the running time.Step 2
The cycle check with union-find
An edge closes a cycle exactly when and are already connected by chosen edges. Union-find (disjoint set union) tracks the components: every set has one root, find(x) returns x's root, and union(a, b) merges two sets by pointing one root at the other.
find(x)
Follow parent pointers to the root of x's set. Same root means same component. amortised.
union(a, b)
Link the root of one set under the root of the other. Returns False if they already shared a root. amortised.
Accept or reject: the roots decide
Compare roots with find
- Answers exactly the question that matters: are u and v already connected?
- Near per edge with path compression and union by rank.
- Works no matter how the fragments formed.
Shortcuts that break
- "Both ends visited": rejects edges that join two different fragments.
- Compare
parent[u]andparent[v]: parents are only the next hop, not the root. - Run DFS to look for a path each time: correct but per edge, total.
Under the hood
Path compression and union by rank
A naive union-find can build a long chain, and then every find walks it. Two small tricks keep the trees almost flat. Path compression: after finding the root, point every vertex on the path straight at it. Union by rank: hang the shorter tree under the taller one, where rank is an upper bound on height.
find with path compression
Cost per operation
class DSU: def __init__(self, items): self.parent = {x: x for x in items} self.rank = {x: 0 for x in items} def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) # path compression return self.parent[x] def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False # already connected if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra self.parent[rb] = ra # union by rank if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 return Trued = DSU("ABCDE")print(d.union("A", "B"), d.union("C", "D"), d.union("B", "D")) # True True Trueprint(d.union("A", "D")) # False: cycleprint(d.find("D"), d.parent["D"]) # A A (compressed)Worked example
The computer network
Six machines, nine possible cables. Buying every cable costs 37. Kruskal picks the cheapest cables that still connect everyone.
- 1
Sort
3-4(1),0-2(2),4-5(2),1-4(3),0-1(4),2-4(4),1-2(5),2-5(6),1-3(10). - 2
3-4, 0-2, 4-5
Each joins two different sets. Running total . Groups: {3, 4, 5} and {0, 2}, with 1 alone.
- 3
1-4 (3)
find(1) = 1,find(4) = 3: different. Accept, total 8. Groups: {1, 3, 4, 5} and {0, 2}. - 4
0-1 (4)
find(0) = 0,find(1) = 3: different. Accept, total 12. That is 5 edges for 6 vertices: stop. - 5
What was skipped
2-4,1-2,2-5and1-3are never looked at. The cost-10 link is avoided because machine 3 is reached through 4 for 1.
Why it works
The cut property and the exchange argument
Cut property
Exchange argument
The swap never costs more
Cost
Why O(E log E), and why that equals O(E log V)
Total running time
log E and log V are the same order
Where the time goes
| Phase | Work | Cost |
|---|---|---|
| Make sets | parent[v] = v, rank[v] = 0 | |
| Sort edges | Comparison sort by weight | |
| Scan edges | Up to edges, 2 finds each | |
| Merge | Exactly successful unions |
Compared
Kruskal versus Prim
Prim's algorithm builds the same minimum tree from the other direction: start at any vertex and repeatedly add the cheapest edge leaving the tree, using a priority queue. Both are greedy, both rely on the cut property, and on a graph with distinct weights both return the identical tree.
| Aspect | Kruskal | Prim |
|---|---|---|
| Approach | Edge-centric: sort all edges | Vertex-centric: grow one tree |
| Key structure | Union-find | Priority queue |
| Time | with a heap, with an array | |
| Best for | Sparse graphs, edge lists, pre-sorted edges | Dense graphs, adjacency matrices |
| Midway state | A forest of fragments | One connected tree |
| Disconnected input | Naturally gives a spanning forest | Covers one component per start |
Which one to reach for
In code
A complete implementation and its edge cases
def kruskal_mst(n, edges): parent = list(range(n)) rank = [0] * n def find(x): while parent[x] != x: parent[x] = parent[parent[x]] # path halving: iterative compression x = parent[x] return x mst, total = [], 0 for u, v, w in sorted(edges, key=lambda e: e[2]): ru, rv = find(u), find(v) if ru == rv: continue # would close a cycle if rank[ru] < rank[rv]: ru, rv = rv, ru parent[rv] = ru if rank[ru] == rank[rv]: rank[ru] += 1 mst.append((u, v, w)) total += w if len(mst) == n - 1: break # tree complete return (mst, total) if len(mst) == n - 1 or n <= 1 else Noneedges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)]print(kruskal_mst(4, edges)) # ([(1, 2, 1), (1, 3, 2), (0, 2, 3)], 6)print(kruskal_mst(4, [(0, 1, 1), (2, 3, 1)])) # None: two separate componentsDisconnected graph
Edges run out with fewer than accepted. You have a minimum spanning forest of edges for components. Report it or return -1.
Equal weights
Any tie order gives a valid MST with the same total. The tree itself may differ.
Negative weights
Fine. Kruskal only compares weights, so negative edges need no special care, unlike Dijkstra.
Self-loops and parallel edges
A self-loop has find(u) = find(v) and is rejected automatically. Of parallel edges, the cheapest is seen first.
Variations
Same loop, other questions
Maximum spanning tree
Sort descending (or negate weights). Used for the widest-bandwidth backbone.
k clusters
Stop when components remain. The next edge Kruskal would accept is the spacing between clusters, and it is the largest possible.
Critical edges
An edge is critical if removing it raises the MST weight. Test it by rerunning Kruskal without it: for all edges.
Connect all points
A complete graph of Manhattan or Euclidean distances: , so Prim's often wins.
Single-link clustering with Kruskal
Recap
Key takeaways
Kruskal fits when
- You need the cheapest way to connect everything: networks, roads, pipes, wiring.
- The graph is given as a list of weighted edges, or is sparse.
- Edges are already sorted, or weights are small integers.
- You want clusters: stop early at components.
Look elsewhere when
- You need shortest paths between vertices: use Dijkstra.
- The graph is directed: use Chu-Liu/Edmonds.
- The graph is dense or a full distance matrix: Prim's is better.
Key points
- An MST connects all vertices with edges of least total weight; it is unique when weights are distinct.
- Kruskal: sort edges ascending, accept an edge when
find(u) != find(v)and union them, stop at edges. - Union-find with path compression and union by rank makes each check , effectively constant.
- Time , dominated by the sort; space .
- Correctness: each accepted edge is the lightest edge crossing the cut around its component, so the cut property makes it safe.
- Prim grows one tree with a priority queue and suits dense graphs; Kruskal merges a forest and suits sparse edge lists.