Watch union find merge groups and find each root, with path compression and union by rank animated. Worked example growing one group from 0 to 3, or your own.
About this algorithm
A disjoint set union, or union-find, keeps elements split into groups and answers two questions fast: which group is this element in, and are these two in the same group. Each group is a tree stored in a parent array, and the root of the tree names the group. Union joins two groups by hanging one root under the other.
Use union-find when groups only ever merge and you keep asking whether two items are connected: friend circles, pixels of one colour, accounts that share an email, or Kruskal's minimum spanning tree. Each question costs nearly constant time. Pick BFS or DFS on the graph instead when you need the actual path between two items, or when connections can be removed, because union-find cannot split a group. This page lets you run each operation by hand; the components and cycle detection pages run union over a fixed list of edges.
Set parent[i] = i for all 7 nodes and every rank to 0: seven separate groups.
Follow parent links from x until you reach a node that is its own parent. On this page Find also compresses the path: every node passed on the way is re-linked straight to the root, so the next Find from any of them takes one hop.
Find the roots of x and y. If they match, x and y are already together and nothing changes. Otherwise the root with the lower rank goes under the other. On a tie, y's root goes under x's root and x's root gains one rank. Rank is an upper bound on a tree's height, so this keeps trees shallow.
Two nodes are in the same group exactly when their roots are the same node.
The page starts with nodes 0 to 6 apart and the inputs set to 0 and 1, so Play runs Union(0, 1): both are roots of rank 0, so 1 goes under 0 and 0's rank becomes 1. Union(2, 3) puts 3 under 2 the same way. Now Union(1, 3): the root of 1 is 0 and the root of 3 is 2, both of rank 1, so 2 goes under 0 and 0's rank becomes 2. Node 3 now sits two hops from its root, 3 to 2 to 0. Find(3) walks that path and then points 3 straight at 0. Connected(0, 3) answers yes, root 0, and Connected(0, 4) answers no, since 4 is still its own root. Each operation works on the forest the last one left, until you reload the page.
With union by rank alone, a tree of rank r holds at least 2^r nodes, so no Find takes more than log₂ N hops. Adding path compression brings the average cost per operation down to α(N), the inverse Ackermann function, which is at most 4 for any input that fits in a computer. On this page only the Find button compresses; Union and Connected look up roots without changing any links.
Time: union by rank caps every tree at log₂ N levels, so a single operation is O(log N) at worst; with path compression as well, a long run of operations averages O(α(N)) each. Space: one parent entry and one rank entry per element.