This is the canonical Union-Find problem. It teaches you to detect cycles in undirected graphs efficiently.
Enable JavaScript for the full StreamPrep guide.