Redundant Connection II
Hard
Topics
A rooted tree is a directed graph where every node has exactly one parent except the root, which has none. You start with such a tree on n nodes labelled 1 to n and add one extra directed edge.
Given the resulting edges list, where edges[i] = [u, v] is a directed edge from parent u to child v, return the edge that can be removed so the remaining graph is a rooted tree of n nodes. If several answers exist, return the one that appears last in the input.
Example 1
[parent, child] over nodes 1..n.Input: edges = [[1,2],[1,3],[2,3]] Output: [2,3] Explanation: Node 3 has two parents. Removing the later of the two edges into it leaves a valid rooted tree.
Example 2
Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]] Output: [4,1] Explanation: Every node has one parent, so the fault is a cycle. Removing the edge that closes it restores the tree.
Constraints
- n == edges.length
- 3 <= n <= 1000
- edges[i].length == 2
- 1 <= u, v <= n
- u != v
Editorial — intuition, approach, complexity and pitfalls
Intuition
Adding one directed edge to a rooted tree breaks it in exactly one of two ways: some node ends up with two parents, or the graph gains a cycle while every node still has one parent. Both can happen at once — the extra edge creates a second parent and closes a cycle — and that overlap is the whole difficulty. Detect the two-parent case first, then let union-find decide which of the two candidate edges to discard.
Approach
- Scan the edges and record a parent for each child. If a child already has one, remember the two competing edges as
first(the earlier one) andsecond(the later one). - If no node has two parents, run union-find over all edges and return the first edge whose endpoints are already connected — that edge closes the cycle.
- If a node does have two parents, run union-find again but skip
second. If all remaining unions succeed, the graph withoutsecondis a valid tree, so returnsecond. - If skipping
secondstill leaves a cycle, thenfirstis the edge tangled up in it, so returnfirstinstead.
class Solution:
def findRedundantDirectedConnection(self, edges):
n = len(edges)
parent_of = {}
first = second = None
for u, v in edges:
if v in parent_of:
first = [parent_of[v], v]
second = [u, v]
else:
parent_of[v] = u
root = list(range(n + 1))
def find(x):
while root[x] != x:
root[x] = root[root[x]]
x = root[x]
return x
for u, v in edges:
if second is not None and [u, v] == second:
continue
ru, rv = find(u), find(v)
if ru == rv:
return first if second is not None else [u, v]
root[rv] = ru
return secondDry Run
Two different defects are possible, and they need different answers, so the
solution asks two questions in two passes.
edges = 1->2, 1->3, 2->3
pass 1 -- does any node have two parents?
edge 1->2 parent_of[2] = 1
edge 1->3 parent_of[3] = 1
edge 2->3 3 already has parent 1, so record both candidates
first = [1,3] second = [2,3]
pass 2 -- union every edge EXCEPT second, and see whether a cycle survives.
edge 1->2 find(1)=1 find(2)=2 roots differ, union[1]=2
edge 1->3 find(1)=2 find(3)=3 roots differ, union[2]=3
edge 2->3 skipped, it is second
no cycle survived, so removing second was enough answer 2 3
Now the other branch of the same code, on edges = 2->1, 3->1, 4->2, 1->4:
pass 1 parent_of[1] = 2, then 3->1 collides first = [2,1] second = [3,1]
pass 2 2->1 union[2]=1 ; 3->1 skipped ; 4->2 union[4]=1
1->4 find(1)=1 find(4)=1 same root -- a cycle is still there
second was load-bearing, so the other candidate is the culprit
answer 2 1
And when no node has two parents the only possible defect is a plain cycle, so the
edge that closes it is the answer: on 1->2, 2->3, 3->4, 4->1, 1->5 the unions run
1,2,3 and then 4->1 finds find(4) = find(1) = 4, and with first still None the
cycle-closing edge itself is returned -- answer 4 1.
Skipping second during pass 2 is the trick that lets one union-find pass settle
both questions at once.Complexity
- Time — O(n a(n)) — two linear scans with near-constant union-find operations.
- Space — O(n) for the parent map and union-find roots.
Common Pitfalls
- Returning
secondunconditionally in the two-parent case is the classic wrong answer. Whenfirstalso lies on a cycle, removingsecondleaves the cycle intact. - Comparing candidate edges by value can misfire if the input repeats a pair. Track the index instead when duplicates are possible.
- This is not Redundant Connection with a direction bolted on. The undirected version only ever has the cycle case, so plain union-find is not sufficient here.
- Labels run from 1 to n, so size the union-find array
n + 1or you will read out of bounds.
Full Solution — all languages
class Solution:
def findRedundantDirectedConnection(self, edges):
n = 0
for u, v in edges:
n = max(n, u, v)
parent_of = {}
first = second = None
for u, v in edges:
if v in parent_of:
first = [parent_of[v], v]
second = [u, v]
else:
parent_of[v] = u
union = list(range(n + 1))
def find(x):
while union[x] != x:
union[x] = union[union[x]]
x = union[x]
return x
for u, v in edges:
if second is not None and u == second[0] and v == second[1]:
continue
a, b = find(u), find(v)
if a == b:
return first if first is not None else [u, v]
union[a] = b
return secondimport java.util.*;
class Solution {
public int[] findRedundantDirectedConnection(int[][] edges) {
int n = 0;
for (int[] e : edges) n = Math.max(n, Math.max(e[0], e[1]));
Map<Integer, Integer> parentOf = new HashMap<>();
int[] first = null, second = null;
for (int[] e : edges) {
if (parentOf.containsKey(e[1])) {
first = new int[]{parentOf.get(e[1]), e[1]};
second = new int[]{e[0], e[1]};
} else {
parentOf.put(e[1], e[0]);
}
}
union = new int[n + 1];
for (int i = 0; i <= n; i++) union[i] = i;
for (int[] e : edges) {
if (second != null && e[0] == second[0] && e[1] == second[1]) continue;
int a = find(e[0]), b = find(e[1]);
if (a == b) return first != null ? first : new int[]{e[0], e[1]};
union[a] = b;
}
return second;
}
private int[] union;
private int find(int x) {
while (union[x] != x) {
union[x] = union[union[x]];
x = union[x];
}
return x;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
int n = 0;
for (auto& e : edges) n = max(n, max(e[0], e[1]));
unordered_map<int, int> parentOf;
vector<int> first, second;
for (auto& e : edges) {
if (parentOf.count(e[1])) {
first = {parentOf[e[1]], e[1]};
second = {e[0], e[1]};
} else {
parentOf[e[1]] = e[0];
}
}
vector<int> uni(n + 1);
for (int i = 0; i <= n; i++) uni[i] = i;
function<int(int)> find = [&](int x) {
while (uni[x] != x) {
uni[x] = uni[uni[x]];
x = uni[x];
}
return x;
};
for (auto& e : edges) {
if (!second.empty() && e[0] == second[0] && e[1] == second[1]) continue;
int a = find(e[0]), b = find(e[1]);
if (a == b) return first.empty() ? vector<int> {
e[0], e[1]
}
: first;
uni[a] = b;
}
return second;
}
};/**
* @param {number[][]} edges
* @return {number[]}
*/ var findRedundantDirectedConnection = function(edges) {
let n = 0;
for (const e of edges) n = Math.max(n, e[0], e[1]);
const parentOf = new Map();
let first = null, second = null;
for (const e of edges) {
if (parentOf.has(e[1])) {
first = [parentOf.get(e[1]), e[1]];
second = [e[0], e[1]];
} else {
parentOf.set(e[1], e[0]);
}
}
const union = Array.from({ length: n + 1 }, (_, i) => i);
const find = (x) => {
while (union[x] !== x) {
union[x] = union[union[x]];
x = union[x];
}
return x;
};
for (const e of edges) {
if (second && e[0] === second[0] && e[1] === second[1]) continue;
const a = find(e[0]), b = find(e[1]);
if (a === b) return first ? first : [e[0], e[1]];
union[a] = b;
}
return second;
};