GeeksforGeeks Medium

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 − 1 edges 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.

Constraints
  • 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.
graphmstgreedyunion-find
Open on GeeksforGeeks ↗
02

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 of u's tree, and some minimum spanning tree uses it.

Union-find answers "same tree?" in near-constant time.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def spanningTree(self, V, edges):
▶3 parent = list(range(V))
▶4 size = [1] * V
▶5 
▶6 def find(x):
▶7 while parent[x] != x:
▶8 parent[x] = parent[parent[x]]
▶9 x = parent[x]
▶10 return x
▶11 
▶12 total = used = 0
▶13 for u, v, w in sorted(edges, key=lambda e: e[2]):
▶14 ru, rv = find(u), find(v)
▶15 if ru == rv:
▶16 continue
▶17 if size[ru] < size[rv]:
▶18 ru, rv = rv, ru
▶19 parent[rv] = ru
▶20 size[ru] += size[rv]
▶21 total += w
▶22 used += 1
▶23 if used == V - 1:
▶24 break
▶25 return total
trees (union-find sets)012345edges, cheapest first0 – 112 – 314 – 521 – 230 – 343 – 451 – 56total weight0sort the edges; every vertex is its own tree
V6
edges7
trees6
The 7 edges are listed cheapest first, and each of the 6 vertices starts as a tree of its own in union-find. The tree needs 5 edges in all, and each one taken merges two trees into one.
trees (union-find sets)0root12345edges, cheapest first0 – 11taken2 – 314 – 521 – 230 – 343 – 451 – 56total weight10 and 1 are in different trees → take, weight 1
edge0 – 1weight 1
roots0 and 1different trees
edges taken1 of 5
total1
The roots differ (0 and 1), so the edge joins two separate trees. Every cheaper edge has been handled already, so this is the cheapest way out of either tree and is safe to keep. Root 1 hangs under root 0, the root of the bigger tree, and 1 is added to the total.
trees (union-find sets)0root12root345edges, cheapest first0 – 11taken2 – 31taken4 – 521 – 230 – 343 – 451 – 56total weight1+1=22 and 3 are in different trees → take, weight 1
edge2 – 3weight 1
roots2 and 3different trees
edges taken2 of 5
total2
The roots differ (2 and 3), so the edge joins two separate trees. Every cheaper edge has been handled already, so this is the cheapest way out of either tree and is safe to keep. Root 3 hangs under root 2, the root of the bigger tree, and 1 is added to the total.
trees (union-find sets)0root12root34root5edges, cheapest first0 – 11taken2 – 31taken4 – 52taken1 – 230 – 343 – 451 – 56total weight1+1+2=44 and 5 are in different trees → take, weight 2
edge4 – 5weight 2
roots4 and 5different trees
edges taken3 of 5
total4
The roots differ (4 and 5), so the edge joins two separate trees. Every cheaper edge has been handled already, so this is the cheapest way out of either tree and is safe to keep. Root 5 hangs under root 4, the root of the bigger tree, and 2 is added to the total.
trees (union-find sets)0root1234root5edges, cheapest first0 – 11taken2 – 31taken4 – 52taken1 – 23taken0 – 343 – 451 – 56total weight1+1+2+3=71 and 2 are in different trees → take, weight 3
edge1 – 2weight 3
roots0 and 2different trees
edges taken4 of 5
total7
The roots differ (0 and 2), so the edge joins two separate trees. Every cheaper edge has been handled already, so this is the cheapest way out of either tree and is safe to keep. Root 2 hangs under root 0, the root of the bigger tree, and 3 is added to the total.
trees (union-find sets)0root1234root5edges, cheapest first0 – 11taken2 – 31taken4 – 52taken1 – 23taken0 – 34skipped, would close a loop3 – 451 – 56total weight1+1+2+3=70 and 3 share root 0 → skip
edge0 – 3weight 4
roots0 and 0same tree
total7
0 and 3 are already joined through edges taken earlier, so this edge would close a loop. Those earlier edges are all cheaper or equal, so the weight-4 edge is the heaviest on that loop and no minimum tree needs it.
trees (union-find sets)0root12345edges, cheapest first0 – 11taken2 – 31taken4 – 52taken1 – 23taken0 – 34skipped, would close a loop3 – 45taken1 – 56total weight1+1+2+3+5=123 and 4 are in different trees → take, weight 5
edge3 – 4weight 5
roots0 and 4different trees
edges taken5 of 5
total12
The roots differ (0 and 4), so the edge joins two separate trees. Every cheaper edge has been handled already, so this is the cheapest way out of either tree and is safe to keep. Root 4 hangs under root 0, the root of the bigger tree, and 5 is added to the total.
trees (union-find sets)0root12345edges, cheapest first0 – 11taken2 – 31taken4 – 52taken1 – 23taken0 – 34skipped, would close a loop3 – 45taken1 – 56not neededtotal weight1+1+2+3+5=12answer: total weight 12
edges taken5 of 5
answer12
With 5 edges taken, one tree spans all 6 vertices, so the loop stops. The 1 edge never looked at could only close a loop. The minimum spanning tree weighs 12.
05

Common pitfalls

Comparing the endpoints instead of their roots

✗ Wrong
if u == v:
    continue
✓ Right
if find(u) == find(v):
    continue

Two 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

✗ Wrong
parent[u] = v
✓ Right
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

✗ Wrong
for u, v, w in sorted(edges):
✓ Right
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.

06

Edge cases

Several edges with the same weight, e.g. the triangle [[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.

A graph that is not connected

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.

07

Complexity

Time
O(E log E)
Space
O(V + E)
Sorting the edges dominates. Each 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).
08

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.