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 TrueTwo 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 (
unionreturningFalseis the cycle test). Cheapest-way-to-connect-everything: fiber layouts, circuit-board routing, cluster linkage. - Connected components —
scipy.ndimage.labellabels 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_componentsexists 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. networkxhasutils.union_find.UnionFindif 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?
Keep reading
Related articles from the SudoSecurity blog.
Finding a Matrix Inverse Without the Pain
Inverting a matrix feels like magic until you see what it's actually doing: solving n systems of equations at once by row-reducing a doubled matrix. The method is mechanical, and once you see it, you don't forget it. The setup Take your matrix A and write the identity next to it — [A | I]. Now row-reduce until the left side becomes the identity. The right side is A⁻¹. That's the whole method: Gaussian elimination on a wider matrix. [A | I] → row operations → [I | A⁻¹] Every operation that t
STRIPS: The 1971 Paper That's Still the Ancestor of Every Game AI Planner
The 1971 Fikes & Nilsson paper that invented STRIPS planning, read firsthand — and the four changes F.E.A.R.'s GOAP made to run it in real time.
Implementing Your Own Garbage Collector in Java: Memory Allocation, Reference Tracking, and GC Algorithms
This guide walks through designing a fixed-size memory pool, implementing reference counting with cycle detection, coding Mark & Sweep, Mark & Compact, and Copying GC algorithms, and wiring root object identification and sweeping into a working CustomGarbageCollector class.
Solana's Proof of History, Explained
As the blockchain concept expands beyond cryptocurrency into software applications, improving transaction-throughput performance has become a critical area of research and development. One of the more visionary improvements in this area is the Proof of History, introduced by the Solana…