Disjoint Set Union (Union-Find)
Track connected components under merges in near O(1) per operation using path compression and union by rank or size.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Graph Representation, BFS and DFS
DSU answers "are these two elements in the same group?" while groups keep merging. It is simpler than DFS when edges arrive one at a time.
Implementation
- parent[i] starts as i. find(x) follows parents to the root.
- Path compression: point every visited node directly at the root.
- Union by rank or size: attach the smaller tree under the larger.
- With both, operations are almost O(1) (inverse Ackermann).
Key patterns
- Number of connected components after a list of edges (Number of Provinces, Number of Operations to Make Network Connected).
- Detect a cycle in an undirected graph: an edge whose endpoints already share a root (Redundant Connection).
- Kruskal's MST (next topic).
- Grouping by shared attributes: Accounts Merge (union emails), Most Stones Removed with Same Row or Column.
- Online connectivity: Number of Islands II, where land is added one cell at a time.
- Map grid cells to ids with r * cols + c.
Pitfalls
- Comparing parent[a] == parent[b] instead of find(a) == find(b).
- Forgetting to decrement the component count only when a union actually merges two roots.
- Recursion depth in find without path compression on large inputs.
You are ready to move on when you can write DSU with both optimisations in under 15 lines and solve Accounts Merge.
Key concepts
- find and union
- Path compression
- Union by rank or size
- Counting components
- Cycle detection with DSU
- Mapping grid cells and strings to ids
Mini project
Solve these 7 in 5 days, log time and pattern: Number of Provinces (with DSU), Redundant Connection, Number of Operations to Make Network Connected, Accounts Merge, Most Stones Removed with Same Row or Column, Satisfiability of Equality Equations, Number of Islands II.
Check yourself
What goes wrong if you check parent[a] == parent[b] to test whether a and b are connected?
Free resources
- cp-algorithms: Disjoint Set Union (cp-algorithms)
- VisuAlgo: Union-Find DS (VisuAlgo)
- takeUforward graph series (takeUforward)