Graph Theory37 sections · 1633 units
Open in Course

The Union Operation

Merging Groups

To union nodes aa and bb:

1.1. Find the leader of aa. Call it rootA.

2.2. Find the leader of bb. Call it rootB.

3.3. If rootA == rootB, they are already in the same group. Done.

4.4. Otherwise, set parent[rootA] = rootB (or vice versa).

Now everyone in aa's old group points (eventually) to bb's leader. The two groups are merged. This takes O(h)O(h) for the two find calls plus O(1)O(1) for the pointer update.

Space complexity is O(n)O(n) for the data structures used.