Union-Find (Disjoint Set Union)

Track groups of connected elements with near-constant-time union and find operations using path compression and union by rank.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Graph Representation, BFS and DFS

Disjoint Set Union (DSU) maintains a collection of groups and supports two operations: find(x) returns the group representative of x, and union(a, b) merges two groups. It answers "are these two connected?" as edges arrive, without re-running a traversal.

Implementation

Store a parent array where each root points to itself.

  • Path compression: during find, point every visited node directly to the root.
  • Union by rank or size: attach the smaller tree under the larger one.

With both optimisations each operation is O(alpha(n)), effectively constant.

The whole data structure is about 15 lines, so memorise it.

Patterns

  • Dynamic connectivity: number of components after each edge (Number of Provinces, islands being added).
  • Cycle detection in undirected graphs: an edge whose endpoints already share a root creates a cycle (Redundant Connection).
  • Kruskal's MST uses DSU to skip edges that would form a cycle.
  • Grouping by equivalence: Accounts Merge, Satisfiability of Equality Equations, Similar String Groups.
  • Offline queries: sort queries and edges by weight and union as you go.

Limits

DSU does not support splitting groups or listing a group's members efficiently (you would need extra bookkeeping), and it works on undirected connectivity only.

Key concepts

  • Parent array and find
  • Path compression
  • Union by rank or size
  • Counting components
  • Cycle detection with DSU
  • Offline queries sorted by weight

Mini project

Implement a DSU class with size tracking, then solve 6 problems: Number of Provinces, Redundant Connection, Accounts Merge, Number of Operations to Make Network Connected, Satisfiability of Equality Equations, and Most Stones Removed with Same Row or Column.

Check yourself

Without path compression or union by rank, what shape of tree makes find() O(n), and how do the two optimisations prevent it?

Free resources