What is Union-Find (Disjoint Set Union)?

Why Interviewers Ask This

This tests whether you can apply Data Structures & Algorithms knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

Union-Find (Disjoint Set Union, DSU) is a data structure that efficiently tracks which elements belong to the same group (set) and supports merging groups. Operations: find(x) — return the representative (root) of x's set; union(x, y) — merge the sets containing x and y. Optimizations: (1) Path compression: in find(), make every node on the path point directly to the root — flattens the tree for future finds; (2) Union by rank/size: in union(), attach the smaller tree under the root of the larger — keeps trees shallow. With both optimizations: nearly O(1) per operation — amortized O(α(n)) where α is the inverse Ackermann function (essentially constant for all practical n). Implementation: array where parent[i] = parent of i (root[i] == i for roots). Applications: (1) Kruskal's MST — detect cycle before adding edge; (2) Number of connected components in a graph; (3) Percolation theory; (4) Dynamic connectivity queries; (5) Social network grouping; (6) Redundant connections detection. DSU is one of the most useful and elegant data structures — simple to implement with massive impact.

Pro Tip

This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.