Union-Find (Disjoint Set) Pattern
Union-Find (DSU) tracks a partition of elements into disjoint sets, answering 'are these connected?' and merging sets almost in O(1) with path compression and union by rank. It's the fast way to reason about connectivity as edges arrive.
Typical complexity: Near O(1) per operation (inverse-Ackermann amortized)
When to use it
- You repeatedly merge groups and check membership.
- The problem is about connected components or cycle detection in an undirected graph.
- Edges are added incrementally.
Practice problems
Read the approach or generate an interactive, step-by-step lesson:
Deep dive
Union-Find Pattern: The Cleanest Way to Track Connected Components
Understand disjoint set union, path compression, and union by rank so you can solve connectivity problems efficiently.
Master union-find (disjoint set) by doing
codebrew.ai turns each problem into an interactive lesson — trace the algorithm variable by variable until the pattern clicks.
Start a free lesson