PrepStack · Markdown HTML

Kruskal minimum spanning tree

DSU, MST, and offline activation · HTML

Formal shape

For G=(V,E) with comparable weights, find a spanning tree T of |V|-1 edges minimizing their total weight.

Recognition signals

False friends

SignalWhy it is different
Single-source shortest pathsAn MST minimizes the tree's total weight, not the path from one source to each vertex.
Directed minimum connectionOrdinary Kruskal is for undirected graphs; directed spanning structures need different machinery.

Core invariant

After each scanned weight, the chosen forest can be extended to some MST; accept only the lightest edge crossing two current components.

State, transition, and processing order

ItemDefinition
StateSorted edges, a DSU for the forest, accumulated total, and chosen edges.
TransitionRead edges in nondecreasing weight; accept and add the weight when union succeeds, otherwise reject the cycle-forming edge.
Frontier / orderUnscanned edges form a weight-ordered frontier; the lightest cross-component edge is safe by the cut property.

Python skeleton

def kruskal(n, edges):
    p, sz = list(range(n)), [1] * n
    def find(x):
        while x != p[x]:
            p[x] = p[p[x]]; x = p[x]
        return x
    def union(a, b):
        a, b = find(a), find(b)
        if a == b: return False
        if sz[a] < sz[b]: a, b = b, a
        p[b] = a; sz[a] += sz[b]
        return True
    total, chosen = 0, []
    for w, u, v in sorted(edges):
        if union(u, v):
            total += w; chosen.append((u, v, w))
            if len(chosen) == n - 1: break
    return (total, chosen) if len(chosen) == n - 1 else None

Correctness sketch

  1. The cut property places a lightest edge across any current cut in some MST.
  2. Weight order makes an accepted edge no heavier than any unprocessed replacement.
  3. DSU rejects intra-component edges, so the chosen set stays acyclic.
  4. In a connected graph, n-1 consecutive safe choices form an MST.

Complexity

TimeSpaceParameters
O(E log E), dominated by sortingO(V+E)V vertices and E edges; DSU work is O(E α(V))

Edge cases

Error patterns

PatternWhy it fails / fix
Sorting the wrong tuple fieldFor (u,v,w), provide an explicit weight key or store (w,u,v).
Scanning after V-1 choicesThe tree is already complete; stop early.
Skipping the connectivity checkFewer than V-1 choices yield only a forest, not a spanning tree.

Selection and exclusion rules

RelationTemplateBoundary
bottleneck relationMinimax / bottleneck DijkstraOnly the minimum possible maximum edge on a two-vertex path matters
shared sorted skeletonOffline activation with DSUEdge weights are activation thresholds

Original micro-example

PartDetail
ResultChoosing 1, 2, and 3 connects all stations for total 6.
ScenarioFour stations have candidate edge weights 2, 1, 3, 8, and 5.
WalkthroughThe first three safe edges complete the tree, so expensive edges need not be scanned.

Recall prompts

My notes