Union-find (disjoint set union) answers "are u and v already connected?" almost instantly while edges are being added one at a time. That makes it the natural tool for spotting the edge that first closes a cycle.
A server room's n machines, labelled 1 .. n, were cabled as a tree: exactly one route between any two machines. Then someone plugged in one extra cable, which closed a loop. The list edges (length n) holds every cable as [u, v]. Write find_redundant_connection(edges) that returns a cable whose removal turns the network back into a tree. Any cable on the loop would do, so return the one that comes last in edges.
Examples
Input: edges = [[2, 3], [1, 2], [1, 3]]
Output: [1, 3]
Input: edges = [[3, 4], [1, 3], [4, 5], [1, 5], [2, 5]]
Output: [1, 5]
Explanation: the loop is 1 - 3 - 4 - 5 - 1; cable [2, 5] comes later but is not on it
Constraints
edgesis a tree on the nodes1 .. n(wheren = len(edges)) plus one extra edge; no edge is repeated- Target: nearly O(n) time with path compression (O(n * alpha(n)))
Goals
- Implement union-find with a parent array, path compression and union by size/rank
- Detect a cycle in an undirected graph by noticing a union of two already-connected nodes
- Process edges incrementally instead of rebuilding a graph each time