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 ProblemValid Tree (n-1 edges)123Connected, No Cycles+Extra EdgeWith Redundant Edge123Creates Cycle!Cycle: 1→2→3→1Goal: Remove the redundant edge to restore tree structureInput: [[1,2],[1,3],[2,3]] → Output: [2,3]
Understanding the Visualization
1
Input: Tree + 1 Edge
Graph with n nodes and n edges (one extra)
2
Process: Find Cycle
Identify which edge creates the cycle
3
Output: Redundant Edge
Return the last edge that completes a cycle
Key Takeaway
🎯 Key Insight: The redundant edge always connects two nodes that are already connected through other paths
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