AlgoViz

Kruskal's algorithm

medium 20 min

Kruskal's algorithm finds a minimum spanning tree: the cheapest set of edges that connects every vertex with no cycles.

See it run

Sort every edge by weight, then walk the list cheapest first, keeping an edge only when union-find says its two ends are still in different sets.

Operations

Simple graph

Six vertices, nine weighted edges. Sort, then accept edges cheapest first until the tree has V − 1 = 5 edges.

Step 1 of 8

Every vertex is its own set

431245261Aset ABset BCset CDset DEset EFset F

Edges, input order

A-B(4) · A-C(3) · B-C(1) · B-D(2) · C-D(4) · C-E(5) · D-E(2) · D-F(6) · E-F(1)

MST, total 0

empty

Union-find starts with six singleton sets: each vertex is its own root, shown as set X under it. The MST is empty and its total is 0.

Step 1: Every vertex is its own set

def kruskal(vertices, edges):    parent = {v: v for v in vertices}       # every vertex is its own set    rank = {v: 0 for v in vertices}    def find(x):        if parent[x] != x:            parent[x] = find(parent[x])     # path compression        return parent[x]    def union(a, b):        ra, rb = find(a), find(b)        if ra == rb:            return False                    # same set: edge closes a cycle        if rank[ra] < rank[rb]:            ra, rb = rb, ra        parent[rb] = ra                     # shorter tree hangs under taller        if rank[ra] == rank[rb]:            rank[ra] += 1        return True    mst, total = [], 0    order = sorted(edges, key=lambda e: e[2])   # O(E log E)    for u, v, w in order:        if union(u, v):            mst.append((u, v, w))            total += w            if len(mst) == len(vertices) - 1:                break                       # V - 1 edges: tree complete    return mst, totaledges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 1), ("B", "D", 2), ("C", "D", 4),         ("C", "E", 5), ("D", "E", 2), ("D", "F", 6), ("E", "F", 1)]print(kruskal("ABCDEF", edges))# ([('B', 'C', 1), ('E', 'F', 1), ('B', 'D', 2), ('D', 'E', 2), ('A', 'C', 3)], 9)
Time
O(E log E)
Space
O(V + E)
edges examined
5 of 9
MST weight
9

Early exit at V − 1 edges is free speed: on this graph it skips almost half the sorted list.

In the real world

The same kruskal's algorithm doing real jobs. Pick one and step through it.

Each island starts as its own country. Build the cheapest bridges first, and never build one between islands that are already in the same country.

Step 1 of 5

Four countries

23457Pset PQset QRset RSset S

Sorted, still to check

P-Q(2) · Q-R(3) · P-R(4) · R-S(5) · Q-S(7)

MST, total 0

empty

Rejected (cycle)

empty

Islands P, Q, R and S, five possible bridges. Every island is its own country.

Step 1: Four countries

bridges = [("P", "Q", 2), ("Q", "R", 3), ("P", "R", 4), ("R", "S", 5), ("Q", "S", 7)]print(kruskal("PQRS", bridges))# ([('P', 'Q', 2), ('Q', 'R', 3), ('R', 'S', 5)], 10)

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Forgetting to sort, or sorting by the wrong field

    critical

    Kruskal's greedy choice is only safe when edges come cheapest first. Processing edges in input order, or sorting tuples (u, v, w) by their first field, builds a spanning tree that is usually not minimal.

    Wrong
    for u, v, w in sorted(edges):      # sorts by u, not weight    if union(u, v):        mst.append((u, v, w))
    Right
    for u, v, w in sorted(edges, key=lambda e: e[2]):    if union(u, v):        mst.append((u, v, w))
  • Using a visited set as the cycle check

    critical

    Two vertices can both be in some tree fragment yet sit in different fragments. Skipping every edge whose ends are both visited throws away the edges that join fragments, so the result is a forest, not a tree.

    Wrong
    seen = set()for u, v, w in order:    if u in seen and v in seen:        continue                     # wrong: may be different fragments    seen |= {u, v}    mst.append((u, v, w))
    Right
    for u, v, w in order:    if find(u) != find(v):           # really different components?        union(u, v)        mst.append((u, v, w))
  • Comparing parents instead of roots

    critical

    parent[x] is only the next hop. Two vertices in the same set can have different parents (D → C → A and B → A), so comparing parents lets a cycle through.

    Wrong
    if parent[u] != parent[v]:    union(u, v)
    Right
    if find(u) != find(v):    union(u, v)
  • Linking the vertices instead of their roots

    critical

    Setting parent[u] = v cuts u off from its old root and leaves the rest of u's set behind, so later finds give wrong answers.

    Wrong
    def union(u, v):    parent[u] = v
    Right
    def union(u, v):    ru, rv = find(u), find(v)    if ru != rv:        parent[ru] = rv
  • Returning a partial tree for a disconnected graph

    major

    If the graph is not connected, the edges run out before V - 1 are accepted. The result is a minimum spanning forest, and callers asking "what does it cost to connect everything?" need to hear that it is impossible.

    Wrong
    mst, total = kruskal(vertices, edges)return total
    Right
    mst, total = kruskal(vertices, edges)if len(mst) != len(vertices) - 1:    return -1                        # graph is disconnectedreturn total
  • Union-find with neither path compression nor union by rank

    minor

    Without them, unions can build a chain of length V and every find walks it: O(V) per check and O(EV) overall. Either trick alone makes it O(log V); both together give O(α(V)), effectively constant.

    Wrong
    def find(x):    while parent[x] != x:        x = parent[x]    return x
    Right
    def find(x):    if parent[x] != x:        parent[x] = find(parent[x])  # compress the path    return parent[x]

Interview tips

  • How to explain it

    • Sort all edges by weight. Walk them cheapest first and keep an edge only if its ends are in different components.
    • Union-find answers "different components?" in near O(1): compare find(u) and find(v), then union them.
    • Stop after V - 1 edges. Time O(E log E) for the sort, space O(V + E).
  • Why it is correct

    • Cut property: the lightest edge crossing any cut belongs to some MST.
    • An accepted edge is the lightest edge leaving its endpoint's component, so it is safe.
    • A rejected edge closes a cycle and is the heaviest edge on it, so no MST needs it.
  • Memory trick: SAFE

    • Sort edges by weight.
    • Add the edge if it makes no cycle.
    • Find the components with union-find.
    • Edge accepted or rejected, until V - 1 are in.
  • Kruskal or Prim?

    • Edge list, sparse graph, or edges already sorted: Kruskal.
    • Dense graph or adjacency matrix: Prim with an array, O(V²).
    • Kruskal grows a forest that merges; Prim grows one tree from a start vertex.