Redundant Connection II - Problem

In this problem, a rooted tree is a directed graph such that there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u_i, v_i] that represents a directed edge connecting nodes u_i and v_i, where u_i is a parent of child v_i.

Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

Input & Output

Example 1 — Node with Two Parents
$ Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
💡 Note: Node 3 has two parents: 1 and 2. Removing the later edge [2,3] creates a valid rooted tree with root 1.
Example 2 — Cycle without Double Parent
$ Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]
💡 Note: There's a cycle 1→2→3→4→1. No node has two parents, so we remove the last edge in the cycle.
Example 3 — Simple Case
$ Input: edges = [[1,2],[2,3],[3,1]]
Output: [3,1]
💡 Note: Forms a cycle 1→2→3→1. The last edge [3,1] creates the cycle, so remove it.

Constraints

  • 3 ≤ edges.length ≤ 1000
  • edges[i].length == 2
  • 1 ≤ ui, vi ≤ edges.length
  • ui ≠ vi

Visualization

Tap to expand
Redundant Connection II: Fix the Tree132[1,3] ✓[2,3] ✗Node 3: Two Parents!After Removing [2,3]13✓ Valid TreeRemove: [2,3] (later edge to node with 2 parents)
Understanding the Visualization
1
Input Graph
Rooted tree with one extra edge added
2
Identify Problem
Find node with 2 parents OR cycle
3
Remove Edge
Return edge that restores valid tree
Key Takeaway
🎯 Key Insight: Only two cases exist - node with two parents, or cycle without double parents
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
98.2K Views
Medium Frequency
~35 min Avg. Time
1.8K 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