Union sequence
Warm-up · Trace the algorithm · about 6 min
Six items A to F start in their own sets. Run union(D, A), union(B, E), union(F, C), union(E, A) with union by size. On a tie, union(x, y) puts the root of y under the root of x. Answer each question before the step plays.
Example 1
Input:
{"n":6,"names":"letters","ops":["union D A","union B E","union F C","union E A"],"groups":true}
Output:
["B","A","D","E","F","C"]
Constraints
- Union by size; on a tie the second root goes under the first
- No path compression is needed here: every find takes at most one hop
Learn the idea first: Disjoint set union: find, union, rank, path compression, a visual lesson.
More Disjoint set union: find, union, rank, path compression problems
- Follow the parent arrows Warm-up
- Implement DSU Standard
- Number of components Standard
- Spot the bug: union without roots Standard
- Implement with union by size and compression Challenge