Skip to the content.

18. Minimum Spanning Tree (Kruskal’s Algorithm)

Back to the index

Connect every node of a weighted undirected graph with the cheapest possible set of edges and no cycles. Kruskal’s algorithm sorts edges by weight and keeps each one that joins two different components, using union-find.

How it works

A spanning tree of a connected graph with V nodes uses exactly V - 1 edges and reaches every node. The minimum spanning tree has the smallest total weight (network cabling, clustering, approximating harder problems).

Kruskal’s algorithm is greedy: sort all edges from lightest to heaviest and walk the list. If an edge connects two nodes that are not yet connected, take it and union their components; if they are already connected, the edge would close a cycle, so skip it. Stop after V - 1 edges. The greedy choice is safe because the lightest edge crossing any split of the nodes always belongs to some minimum spanning tree.

Diagram

graph LR
    A ---|4| B
    A ===|1| C
    B ===|2| C
    B ===|5| D
    C ---|8| D
    C ---|10| E
    D ===|2| E
    B ---|6| E

Step-by-step trace

Input: Undirected graph above (thick links are the result). Edges sorted by weight, ties by endpoints.

Edge (sorted by weight) Weight Decision MST weight so far
A - C 1 take it (joins two components) 1
B - C 2 take it (joins two components) 3
D - E 2 take it (joins two components) 5
A - B 4 skip: same component, would form a cycle 5
B - D 5 take it (joins two components) 10
B - E 6 not needed: tree already has n - 1 edges 10
C - D 8 not needed: tree already has n - 1 edges 10
C - E 10 not needed: tree already has n - 1 edges 10

Result: MST weight 10 using A-C, B-C, D-E, B-D.

Complexity

Operation Time Space
Kruskal (sort + union-find) O(E log E) O(V + E)
Prim with a binary heap O(E log V) O(V + E)

Python reference implementation

def kruskal(n, edges):
    """edges: list of (weight, u, v). Returns (total weight, chosen edges)."""
    uf = UnionFind(n)
    total, chosen = 0, []
    for w, u, v in sorted(edges):
        if uf.union(u, v):          # skip edges that would close a cycle
            total += w
            chosen.append((w, u, v))
            if len(chosen) == n - 1:
                break
    return total, chosen

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Union-Find (Disjoint Set Union) Next: Bubble Sort