Advanced topics · Exercise 89 of 100
Disjoint sets (union-find)
Start each item in its own set, with a parent link pointing to itself. To find the set an item belongs to, follow parent links until you reach a root. To unite two sets, link one root to the other only if the roots differ, so repeated joins preserve the group.
Try it yourself
Start with seven separate items numbered 1 through 7. Join the pairs (1, 2), (3, 4), (2, 4), (6, 7) and (1, 3) in order. How many items end up in the set containing 4?
One-step hint
Start with seven singleton circles. Merge the circles containing each pair, skipping a merge if they are already together. Count the labels in the circle containing 4.
Worked solution
- The first two joins form the pairs {1, 2} and {3, 4}. Joining 2 to 4 merges the pairs into {1, 2, 3, 4}.
- Joining 6 to 7 affects a separate set, and 1 and 3 already share a set. The set containing 4 therefore has 4 items.