Skip to interview prep
Apexed

27. Explain union-find with path compression and union by rank.

MediumDisjoint sets

Technical

Type or dictate your answer. Your draft is saved on this device.

Show model answer

A disjoint-set structure tracks which elements belong to the same group. find(x) follows parent pointers to the set's root; union(a, b) links one root under the other.

Union by rank (or size) attaches the shorter tree under the taller one, and path compression points nodes on a find path directly at the root. Together they make each operation run in near-constant amortized time, O(α(n)). Uses include Kruskal's minimum spanning tree, connected components and cycle detection in undirected graphs.

Example program

Explain union-find with path compression and union by rank. — Data structures & algorithms interview question — Apexed