Detect cycles in an undirected graph using Disjoint Set Union. Watch each edge get tested: if two nodes already share a root, adding that edge creates a cycle.
About this algorithm
An undirected graph has a cycle exactly when some edge joins two nodes that are already connected. Union-find checks this one edge at a time: if both ends already share a root, a path between them exists and the new edge closes a loop. Otherwise the edge is safe and the two groups merge.
Use it when edges arrive one at a time and each must be accepted or rejected: Kruskal's algorithm skips any edge that would form a cycle, Redundant Connection (LeetCode 684) asks for the edge that closes the loop, and Graph Valid Tree checks for N - 1 edges and no cycle. A DFS that remembers each node's parent also finds cycles in O(V + E) and can return the loop itself, but it needs the whole graph first. Neither method works as written on directed graphs, where an edge into an already reached node is not always a cycle; there, use DFS with three colours or Kahn's topological sort.
One group per node, no edges added yet.
Find the roots of its two ends.
The two ends are already joined through earlier edges, so this edge makes a loop. The page marks it red, keeps scanning so you can see every edge, and at the end names the first edge that closed a cycle.
Union the two groups by rank and mark the edge as added.
The first preset holds 7 nodes and the edges (0, 1), (1, 2), (2, 3), (0, 3) and (3, 4). (0, 1) joins two single nodes: 1 goes under 0. (1, 2) finds roots 0 and 2, so 2 goes under 0. (2, 3) puts 3 under 0 as well. Now (0, 3): both ends have root 0. The path 0, 1, 2, 3 already connects them, so this edge closes a square and is marked as the cycle. (3, 4) is still tested and is safe, so 4 joins root 0. The page reports a cycle, first found at edge (0, 3). The second preset finds its cycle at (0, 2), the fourth of its five edges, and the third preset, a ring of six nodes, closes it with its last edge, (5, 0).
Union-find says which edge closed a loop but not which nodes the loop runs through, because its trees record groups, not the original edges. To print the cycle, keep adjacency lists too and search for the path between the two ends of the edge that failed.
Time: each of the E edges costs two finds and at most one union, which is at most log N hops with union by rank, as on this page, and nearly constant with path compression added. Space: a parent and a rank for each node, plus one mark per edge for the drawing.