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
Union gets slow, the tree piles up like a long chain Without union by rank or by size, a union can build a chain n high and every find is O(n). Always hang the short tree under the tall one.
Wanting to undo joining two groups, and it cannot be done A plain DSU keeps nothing of what a union overwrote. Use a rollback variant (a stack of changes, without path compression) or a persistent structure.
find() turns out to change data though it only asks Path compression really does write parent[] during find: on purpose, so the next find is short. Do not use it for historical queries.
Try it in this playground
Join two equal trees With equal ranks, the head on top gains one rank.
Watch path compression work A long find rewrites the parent[] of the plots on its way.
A union that answers false Two plots in one group already: Kruskal skips it.
connected without a direct union Two plots can be one group through others.