Visualize how Union-Find builds connected components from a list of edges. Watch components merge as each edge is processed in O(E·α(N)) total time.
About this algorithm
Given N nodes and a list of undirected edges, this finds which nodes belong together and how many separate groups there are. Start with every node alone, union the two ends of each edge, and the groups left at the end are the connected components. The count drops by one for every edge that joins two different groups.
Use it when edges come as a list, perhaps arriving over time, and you want the number of groups or a quick same-group check after each one: islands added one at a time, network links coming up, or LeetCode's Number of Provinces and Number of Connected Components. Graph BFS or DFS solves the same problem in O(V + E) when the whole graph is known up front as adjacency lists. Union-find wins when edges stream in, because each new edge costs almost nothing and nothing has to be searched again. The cycle detection page runs this same loop but cares about the edges that land inside one group.
Set parent[i] = i for every node. The component count is N.
Take the edge (u, v) and climb from u and from v to their roots.
Hang the lower-rank root under the higher one (on a tie, v's root goes under u's) and subtract one from the count.
u and v are already linked through earlier edges, so this edge adds no new connection and the count stays as it is.
After the last edge, nodes that share a root form one component.
The page loads 7 nodes with the edges (0, 1), (2, 3), (4, 5), (0, 2) and (4, 6). Start with 7 groups. (0, 1) puts 1 under 0: 6 groups. (2, 3) puts 3 under 2: 5 groups. (4, 5) puts 5 under 4: 4 groups. (0, 2) joins roots 0 and 2, both of rank 1, so 2 goes under 0 and 0's rank becomes 2: 3 groups. (4, 6) puts 6 under 4: 2 groups. The answer is 2 components, {0, 1, 2, 3} with root 0 and {4, 5, 6} with root 4. The Chain preset, edges (0, 1) through (5, 6), ends as one group with every node hanging straight off 0, because each newcomer arrives with rank 0 and goes under the bigger tree. In Star Merge the last edge, (3, 6), finds both ends already under root 0 and is skipped, leaving 3 groups.
If you only need the number, keep a counter that starts at N and goes down on each real merge; there is no need to scan the roots at the end. To list the members, group the nodes by their root in one pass after the last edge.
Time: setting up the parents costs O(N), and each of the E edges does two finds and at most one link; with union by rank alone, as here, a find is at most log N hops, and adding path compression brings it to nearly O(1). Space: one parent and one rank per node; the edges are read one at a time and never stored by the structure.