DIGITAL GURU
Java DSA Portfolio

Union-Find by Rank/Size with Path Compression & Cycle Detection

Master Disjoint Set Union (DSU), Find, Union by Rank, Union by Size, and Path Compression in O(alpha(N)) amortized time.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Formal Definition & Classification Types

Definition: A Disjoint-Set Data Structure (DSU), also known as a Union-Find structure, maintains a collection of non-overlapping (disjoint) dynamic sets, supporting two primary operations in $O(\alpha(N))$ amortized time: `Find(i)` (returns representative set ID) and `Union(i, j)` (merges two sets).

Real-World Analogy

Union-Find is like merging royal kingdoms: **Find** asks *"Who is the ultimate King of this village?"*. **Union** merges two kingdoms under the taller King's throne. **Path Compression** makes every village point directly to the King!

Disjoint Set Data Structure (DSU)

Manages partition of elements into disjoint dynamic sets.

Production Code Example:

DisjointSet.java
public class DisjointSet {
    private int[] parent, rank;
    public DisjointSet(int n) {
        parent = new int[n]; rank = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
    }
    public int find(int i) {
        if (parent[i] == i) return i;
        return parent[i] = find(parent[i]); // Path Compression!
    }
    public boolean union(int i, int j) {
        int rootI = find(i), rootJ = find(j);
        if (rootI == rootJ) return false; // Cycle detected!
        if (rank[rootI] < rank[rootJ]) parent[rootI] = rootJ;
        else if (rank[rootI] > rank[rootJ]) parent[rootJ] = rootI;
        else { parent[rootJ] = rootI; rank[rootI]++; }
        return true;
    }
}

Key Complexity & Algorithmic Takeaways:

When implementing Union-Find by Rank/Size with Path Compression & Cycle Detection in coding interviews and production applications, keep these core guidelines in mind:

  • Time Complexity Analysis: Always evaluate best-case, average-case, and worst-case time complexities ($O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$).
  • Space Complexity & Memory Bounds: Account for auxiliary memory usage, call stack frame recursion overhead, and heap allocations.
  • Edge Cases & Validation: Test empty inputs, null pointers, single-element collections, duplicate values, and integer overflow bounds.
  • Optimal vs Naive Solutions: Start with a clear brute-force solution, then optimize using techniques like Hashing, Two Pointers, Windowing, or Dynamic Programming.

Summary Takeaway:

Mastering Union-Find by Rank/Size with Path Compression & Cycle Detection provides the foundational problem-solving skills needed to pass technical coding interviews at top tech companies and write ultra-performant software systems.

Cycle Detection

If `find(u) == find(v)` before unioning edge `(u, v)`, an undirected graph cycle exists!