← All Exercises
Find the Redundant Edge with Union-Find
intermediatepython
Background
Cycle detection with union-find validates dependency graphs, network topologies, and incremental spanning-tree construction.
Problem
Given edges that form a tree plus at most one extra edge, return the first edge that closes a cycle, or an empty list when the graph is already a tree.
Input
A list of [a, b] undirected edges over nodes labelled 1..n, where n is the largest label in the list.
Output
The first edge [a, b] that connects two already-connected nodes, or [] if none exists.
Sample tests
Sample 1
Input: edges = [[1,2],[1,3],[2,3]]
Expected: [2, 3]
Sample 2
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Expected: [1, 4]
Sample 3
Input: edges = [[1,2],[1,3]]
Expected: []
Your solution
Learning objective
Use union-find to detect when an edge joins two nodes in the same set and stop at the first such edge.