Union-Find (Disjoint Set) Playground

Merge groups & find roots via parent[]. Union-by-rank + path compression: how many hops does the next find take? Step through and watch the forest change. The…

Why it matters

Union-find answers "one group or not?" almost at once: Kruskal uses it to skip edges that close a loop, as do cycle detection, connected components and pixel grouping. Two small tricks, union by rank and path compression, turn O(n) a call into nearly constant.

The key idea

One parent[] array knows who is grouped with whom

Common mistakes

Try it in this playground