TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN
Union-Find (DSU): Dynamic Connectivity in O(1) Amortized
Merge clusters and answer 'are these two servers connected?' almost instantaneously as edges stream in.
union-findgraphsconnectivitycomponents
The core idea
Represent each cluster as a shallow tree pointing to a canonical root. Path compression flattens trees during find, giving O(α(n)) ≈ O(1) amortized connectivity checks.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING UNION-FIND DSU SIM...
What to say out loud
Canonical Python template
class DSU:
def __init__(self, n: int):
self.parent = list(range(n))
self.clusters = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
self.parent[ra] = rb
self.clusters -= 1
return True