MST — Kruskal's Algorithm
MST — Kruskal's Algorithm is a GFG problem (Medium). You get a connected, undirected, weighted graph with V vertices, numbered 0 to V − 1, and a list edges where [u, v, w] joins u and v with weight w.
- Return the total weight of a minimum spanning tree:
V − 1edges that connect every vertex with the smallest possible sum. - Find the MST using Kruskal's algorithm, which looks at the edges from cheapest to most expensive.
E can reach V(V − 1) / 2, about 500,000 edges, so the budget is one sort of the edges plus near-constant work per edge.
- 2 <= V <= 1000
- V - 1 <= E <= V * (V - 1) / 2
- 1 <= w <= 1000
- The graph is connected and has no self-loops or repeated edges.
Intuition
Kruskal's algorithm walks the edges from cheapest to most expensive and keeps an edge unless its two ends are already connected. The kept edges form small trees that merge into one.
- Why a skip is safe: the skipped edge would close a loop, and every other edge on that loop was kept earlier, so none is heavier. The skipped edge is the heaviest on the loop, and no minimum tree needs it.
- Why a take is safe: every cheaper edge has been seen already, and any cheaper edge leaving
u's tree would have been taken and merged. So this edge is the cheapest way out ofu's tree, and some minimum spanning tree uses it.
Union-find answers "same tree?" in near-constant time.
"Connect everything at the lowest total cost" over a plain list of weighted links is an MST, and a list of edges points to Kruskal's: sort it, then use union-find to reject any edge whose ends are already joined. The same sort-plus-union-find pattern solves connecting cities, laying cables and clustering points into k groups.
Approach
Before reading on, take the edges from cheapest to most expensive and decide, for each one, whether a minimum tree could still want it. What do you need to know about its two ends to decide? Aim for O(E log E).
Sort the edges by weight
Sort edges by w, smallest first. In this order an edge is either needed or never needed at the moment it is reached, so one pass decides every edge for good.
Start every vertex as its own tree
Set parent[i] = i and size[i] = 1. Each tree is a set in union-find, named by its root, the one vertex whose parent is itself.
Find the roots of both ends
find(x) climbs parent links to the root, pointing each visited vertex at its grandparent on the way so later climbs are shorter. If u and v have the same root, they are already connected, so the edge would close a loop and is skipped.
Merge the two trees and add the weight
Otherwise hang the smaller tree's root under the larger one and add w to the total. Putting the smaller tree underneath keeps every tree at most about log V levels deep.
Stop after V − 1 edges
A tree on V vertices has exactly V − 1 edges, so once that many are taken every vertex is connected. Any edge left could only close a loop, and the loop can end early.
Code in Python, C++ and Java
Common pitfalls
Comparing the endpoints instead of their roots
if u == v:
continueif find(u) == find(v):
continueTwo different vertices can already be joined through earlier edges. On [[0, 1, 1], [1, 2, 1], [0, 2, 1], [2, 3, 5]] with V = 4, the endpoint test takes all three weight-1 edges of the triangle, stops at 3 edges and returns 3. Vertex 3 is never connected; the right answer is 1 + 1 + 5 = 7.
Linking the vertices instead of the roots
parent[u] = v
parent[find(u)] = find(v)
Overwriting parent[u] cuts u away from its old tree. On [[0, 1, 1], [0, 2, 2], [1, 2, 3], [2, 3, 4]] with V = 4, the second edge re-points 0 from 1 to 2, leaving 1 alone. The weight-3 edge then looks safe, the loop stops at 3 edges, and it returns 6 with vertex 3 never connected; the right answer is 7.
Sorting the edges by their first field
for u, v, w in sorted(edges):
for u, v, w in sorted(edges, key=lambda e: e[2]):
A plain sort orders the lists by u, not by weight. On [[0, 1, 5], [0, 2, 2], [1, 2, 1]] it takes the 5 first and returns 7, while the cheapest tree uses the 1 and the 2 and weighs 3.
Edge cases
[[0, 1, 1], [1, 2, 1], [0, 2, 1]]Any order among equal edges is fine. Different orders can pick different trees, but each of them weighs 2.
The problem promises a connected graph. Without that promise the loop runs out of edges with used < V − 1, and the total is a minimum spanning forest, one tree per piece; check used if you need to tell the caller.
Complexity
find is close to O(1) on average with union by size and path halving, so the pass over the edges is about O(E). The parent and size arrays take O(V), and the sorted copy of the edges takes O(E).MST — Kruskal's Algorithm FAQ
How do I return the edges of the tree, not just the total?
Keep a list and append [u, v, w] at the moment an edge is taken, next to total += w. When the loop stops it holds the V − 1 tree edges in the order Kruskal's chose them, cheapest first.
Is the minimum spanning tree unique?
It is when all the weights are different: then every take and skip is forced. With equal weights several trees can tie, as in a triangle whose three edges all weigh 1, but they always have the same total.
Does Kruskal's algorithm work with negative weights?
Yes. It only ever compares weights to sort them, so negative values just move to the front of the order. The skip and take arguments do not depend on the sign.