Redundant Connection II
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Redundant Connection II
In this problem, a rooted tree is modified by adding exactly one extra edge. The extra edge is directed from parent to child. The resulting graph can have two issues:
- A node has two parents.
- There is a directed cycle.
Strategy
- Check if any node has two parents.
- If yes, test if removing the second edge fixes everything. If not, the first edge was the problem.
- If no node has two parents, simply find the edge that completes a cycle using Union-Find (like Redundant Connection I).
Examples
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Approach 1
Level I: DFS (Recursive Search)
Intuition
This problem involves finding an edge whose removal leaves a rooted tree. We can try removing each edge one by one and check if the resulting graph is a valid rooted tree (all nodes reachable from a single root, no cycles) using DFS.
⏱ O(N^2) by testing removal of each of the N edges.💾 O(N).
Approach 2
Level III: Union-Find + Case Analysis
Intuition
Handle two cases: Case 1 is a node having two parents (two edges pointing to it). Case 2 is a simple cycle. Use DSU to detect which edge completes a cycle after potentially 'skipping' one of the double-parent edges.
⏱ O(N \cdot \alpha(N)).💾 O(N).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.