Skip to content

Lesson 10 of 14 · 17m

Union-Find: Connectivity at Scale

Path compression plus union by rank answers 'can A reach B' in amortized near-O(1) — a BFS per query can't.

You've got a network map of 100,000 nodes and 2 million links, and the question is asked ten million times a day: "can A still reach B?" A BFS per query costs O(V+E) each — that's the wrong tool. Union-find answers the same queries in amortized near-O(1): with path compression and union by rank, Tarjan's bound is the inverse Ackermann function α(n), which stays below 5 for any n that fits in memory. Effectively constant.

The whole thing in twenty lines

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x
    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                       # already connected — cycle edge
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra                   # attach smaller under larger
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True

Two optimizations are what make it fast. Path compression — every find repoints nodes toward the root; the path-halving line above (self.parent[x] = self.parent[self.parent[x]]) is the compressed form, and skipping it degenerates trees into O(log n) chains. Union by rank — attach the shallower tree under the deeper — keeps roots flat. Both together give α(n); either alone is merely good. The memory bill is two arrays, O(n) — nothing fancy.

Where it earns its place

  • Kruskal's MST — sort edges by weight, union endpoints, skip edges whose nodes are already connected (union returning False is the cycle test). Cheapest-way-to-connect-everything: fiber layouts, circuit-board routing, cluster linkage.
  • Connected components — scipy.ndimage.label labels contiguous regions in image arrays; percolation studies and "how many islands" grids are the same question wearing different clothes.
  • Offline connectivity — process all edges up front, then answer reachability in bulk. networkx.connected_components exists too, but it walks components with BFS — fine once, wrong per-query at ten million checks a day.
  • Streaming merges — clustering and entity-resolution pipelines union groups as evidence arrives; "same customer" is a merge operation.

Where it loses

Union-find only merges. Delete an edge — "this link just dropped" — and sets don't unmerge; dynamic connectivity under deletions needs heavier machinery (link-cut trees, or recomputing). If your workload interleaves edge_added / edge_removed / connected?, union-find answers two-thirds of it. There's a middle trick worth knowing: rollback union-find — union saves the overwritten parent/rank on a stack so undo() restores state — which handles backtracking searches without the deletions machinery.

What to actually do

All-edges-known connectivity → DSU in ~20 lines; never ship a find without compression. Need the MST → Kruskal = sort + union-find. Need components once → networkx or scipy.ndimage.label. Need reachability under deletions → stop reaching for union-find.

Field notes

  • len({find(x) for x in nodes}) counts connected components — the root identity doubles as the component label.
  • Grid "islands" problems map cells to indices — id = r*cols + c — and union neighbors; no node objects needed.
  • networkx has utils.union_find.UnionFind if you don't want the twenty lines yourself.
  • Rank by tree height or by size both work; the bound holds either way — pick one, don't mix.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.