Skip to main content

Disjoint Set Union (Union-Find)

DSU Visualization

The Power of DSU

DSU maintains a collection of disjoint sets and supports two operations:
  • Find: Which set does element x belong to?
  • Union: Merge two sets together.
With path compression and union by rank, both operations run in O(α(n)) ≈ O(1) amortized time.
Pattern Recognition Signals:
  • “Connected components” that change over time → DSU
  • “Are x and y in the same group?” → DSU
  • “Merge groups” → DSU
  • “Minimum Spanning Tree” → Kruskal’s + DSU
  • “Online connectivity queries” → DSU

Standard Implementation

The Core Idea: Represent each set as a tree. Each element points to its parent, and the root is the set’s representative. Path Compression: When we find the root of an element, we make all nodes along the path point directly to the root. This flattens the tree, making future queries faster. Union by Rank: When merging two sets, attach the shorter tree under the taller one. This keeps trees balanced. Visual Example:
Why O(α(n))? The inverse Ackermann function α(n) grows incredibly slowly—for any practical n (even n = 10^80), α(n) ≤ 4. So it’s effectively constant time!

Usage


DSU with Size Tracking

Track size of each set for weighted merging.

Pattern 1: Kruskal’s MST

Problem: Find Minimum Spanning Tree of a weighted graph. Why Kruskal + DSU? Kruskal’s algorithm sorts edges by weight and greedily adds each edge if it does not form a cycle. The cycle check is exactly the DSU “are these in the same set?” query. Sort takes O(E log E), and E union/find operations take O(E * alpha(V)), so total is O(E log E). Key insight: An MST of n nodes always has exactly n-1 edges. If fewer edges are used after processing all edges, the graph is disconnected (no spanning tree exists).
Codeforces Problems:

Pattern 2: Cycle Detection

Problem: Detect if adding an edge creates a cycle.

Pattern 3: Connected Components Queries

Problem: Answer “are u and v connected?” after edge additions.

Pattern 4: DSU with Weighted Edges

Track something along the path from node to root.
Application: “A is 5 units more than B” type constraints. Also used in problems like “determine if relationships are consistent” (e.g., “if X says A is heavier than B by 3 kg, and Y says B is heavier than C by 2 kg, what is the difference between A and C?”).
Contest tip: Weighted DSU is commonly tested in problems that give pairwise relative information and ask you to detect contradictions or compute absolute values. If you see “relative differences” or “potentials” between elements in the same group, think weighted DSU.

Pattern 5: Rollback DSU (Offline)

Problem: Process queries where edges can be added AND removed. Solution: Use union by size (no path compression) to enable rollback. Why no path compression? Path compression is irreversible — it flattens the tree structure, making it impossible to “undo” a union. Without path compression, each union only changes one parent pointer, which is easy to save and restore. When to use: Offline dynamic connectivity, divide and conquer on queries, and problems where you need to “undo” merges (e.g., process edges that exist only during a time interval).

Pattern 6: DSU on Tree

Merge child sets when processing nodes bottom-up.

Pattern 7: Bipartiteness Check with DSU

Problem: Check if graph can be 2-colored (bipartite).

Common Mistakes

Mistake 1: Not initializing parent correctly
Mistake 2: Union without find
Mistake 3: Using path compression with rollback Path compression destroys the tree structure needed for rollback.

Complexity Analysis

α(n) is the inverse Ackermann function, effectively constant for all practical n.

Practice Problems

Beginner (1000-1300)

Intermediate (1300-1600)

Advanced (1600-1900)


Key Takeaways

Path Compression

Point nodes directly to root during find.

Union by Rank/Size

Attach smaller tree under larger tree.

Kruskal's MST

Sort edges, greedily add if no cycle.

Near-Constant Time

O(α(n)) per operation with both optimizations.

Next Up

Chapter 17: Segment Trees

Master range queries and point updates with segment trees.