Redundant Connection
Redundant Connection
In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge connects two different vertices and creates exactly one cycle.
Return the edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the edge that occurs last in the input.
Function signature
func FindRedundantConnection(edges [][]int) []int
Examples
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Explanation:
1---2
\ /
3
Edge [2,3] creates a cycle. Removing it leaves a valid tree.
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Explanation:
5
|
1---2
| |
4---3
Edge [1,4] creates a cycle. It appears last among cycle edges.
Constraints
- n == edges.length
- 3 <= n <= 1000
- edges[i].length == 2
- 1 <= ai < bi <= n
- ai != bi
- There are no repeated edges
- The given graph is connected
Hints
- Process edges one by one. The edge that would connect two already-connected nodes creates a cycle.
- Use Union-Find: if union returns false (already connected), that's the redundant edge.
- Return the last such edge found.
Notes
- The graph is 1-indexed, not 0-indexed.
- There's always exactly one redundant edge.
- If multiple edges could be removed, return the one appearing last in the input.
Run tests to see results
No issues detected