Example 1
- Input
- edges = [[1,2],[1,3],[2,3]]
- Output
- [2,3]
Edges (1,2) and (1,3) already connect all three nodes, so adding (2,3) closes the only cycle and removing it restores a tree.
A tree of nodes labelled 1 to n has one extra edge added, which creates exactly one cycle. Return the last input edge whose removal turns the graph back into a tree.
You are given an undirected graph that started as a tree with n nodes labelled from 1 to n, with one additional edge added. The added edge connects two different vertices, and it was not an edge that already existed.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
n == edges.length3 <= n <= 1000edges[i].length == 21 <= ai < bi <= nEdges (1,2) and (1,3) already connect all three nodes, so adding (2,3) closes the only cycle and removing it restores a tree.
The first three edges plus (1,4) form the cycle 1-2-3-4-1, and (1,4) is the last edge of that cycle in the input.
The triangle 1-2-3-1 is the only cycle, and [1,3] is its last input edge. Later edges [3,4] and [4,5] are bridges: removing either disconnects the graph. The answer is therefore not the last edge overall.
All three triangle edges can be removed to restore a tree. Their order makes [1,2] the answer, even though it is lexicographically smallest.
A tree has a unique path between any two nodes. Adding one edge creates exactly one cycle; removing any edge on that cycle restores a tree, but the input order decides which one to return. In Example 1, when [2,3] arrives, earlier edges already provide 2 -> 1 -> 3. This is the last edge of the only cycle, even if later input edges exist outside the cycle. We can detect the existing path by a graph search or remember connected groups with union find.
Reveal Path Check Per Edge: intuition, complexity, and code
When undirected edges arrive in order, track connected components to answer whether the next edge closes an existing path. A single-cycle promise turns the first failed union into the last cycle edge required by the input-order tie-break.