AlgoFrames

Merge or cycle?

Warm-up · Trace the algorithm · about 5 min

Five items A to E start alone. Edges arrive in the order A-B, B-C, D-E, C-A, C-D, E-B. Each edge either merges two groups or closes a cycle. On a merge, the smaller group takes the larger group's root, and a tie keeps the first item's root.

Example 1

Input:

{"n":5,"names":"letters","edges":[[0,1],[1,2],[3,4],[2,0],[2,3],[4,1]],"positions":[[0,0],[1.2,0],[0.6,1.1],[2.4,1.1],[2.4,0]]}

Output:

C-A and E-B close cycles

Constraints

  • Smaller group goes under the larger root
  • On a tie the first item's root wins

Learn the idea first: Union-find applications: connectivity, grouping, redundant edges, a visual lesson.

More Union-find applications: connectivity, grouping, redundant edges problems