Union-Find
Signal: "are these two connected?", number of connected components, merging groups (accounts, friend circles), detecting a cycle in an undirected graph, or connectivity that changes as edges are added over time.
Core idea: keep a forest where each set is a tree identified by its root. find(x) walks to the root; union(a, b) attaches one root under the other. Two optimizations make both operations nearly O(1), specifically O(α(n)), where α is the inverse Ackermann function and is at most 4 for any realistic n:
- Path compression: during
find, point nodes directly at the root. - Union by rank/size: attach the smaller tree under the larger one.
python
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * 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 → this edge closes a cycle
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return TrueUnion-Find vs BFS/DFS: for a static graph, either works. Union-Find shines when edges arrive incrementally and you need connectivity answers along the way, or when you just need to know whether an edge creates a cycle.