How do you check for a cycle in an undirected graph? Iterate through every edge . Before adding the edge, check: are and already in the same component?
If yes, adding this edge creates a cycle. If no, union them and continue.
for each edge (u, v)
if find(u) = find(v) then
cycle detected
else
union(u, v)
This is faster than DFS-based cycle detection when you process edges one by one.