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 has two different vertices chosen from 1 to n, and was not an edge that already existed.

The graph is represented as an array edges of length n where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i in the graph.

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.

Input & Output

Example 1 — Basic Triangle
$ Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
💡 Note: We have nodes 1,2,3. Edges [1,2] and [1,3] form a valid tree. Adding [2,3] creates a cycle 1-2-3-1, so [2,3] is redundant.
Example 2 — Square with Diagonal
$ Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
💡 Note: Path 1-2-3-4 already connects nodes 1 and 4. Edge [1,4] creates cycle and occurs last among cycle-creating edges.
Example 3 — Linear with Back Edge
$ Input: edges = [[1,2],[2,3],[1,3]]
Output: [1,3]
💡 Note: Edges [1,2] and [2,3] form path 1-2-3. Adding [1,3] creates cycle 1-2-3-1, and [1,3] is the last edge.

Constraints

  • 3 ≤ edges.length ≤ 1000
  • edges[i].length == 2
  • 1 ≤ ai < bi ≤ edges.length

Visualization

Tap to expand
Redundant Connection - DFS Cycle Detection INPUT 1 2 3 Redundant edge creates cycle edges array: [1,2] [1,3] [2,3] n = 3 nodes 3 edges (1 extra) ALGORITHM STEPS 1 Build Graph Add edges one by one 2 DFS Check Before adding, check path 3 Detect Cycle If path exists, cycle found 4 Return Edge Last edge causing cycle DFS Traversal: Add [1,2]: graph={1:[2],2:[1]} Add [1,3]: graph has 1,2,3 Check [2,3]: DFS(2-->3) Path: 2-->1-->3 EXISTS! Cycle detected at [2,3] Return [2,3] FINAL RESULT Valid Tree: 1 2 3 No cycle - Valid tree! Output: [2, 3] Edge removed to eliminate cycle OK - Tree restored Key Insight: A tree with n nodes has exactly n-1 edges. When we have n edges, one is redundant and creates a cycle. DFS checks if two nodes are already connected before adding an edge. If connected, adding that edge creates a cycle. Time: O(n^2) for DFS on each edge. Space: O(n) for adjacency list and recursion stack. TutorialsPoint - Redundant Connection | DFS Cycle Detection Approach
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
180.0K Views
Medium Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen