Redundant Connection II
Difficulty: Hard · Pattern: Union-Find · LeetCode #685
A rooted tree (every node has exactly one parent except the root) on nodes 1..n had one extra directed edge added. Return the edge that can be removed so that the result is a rooted tree again. If several edges work, return the one that appears last in edges.
Examples
text
[[1,2],[1,3],[2,3]] → [2,3] (node 3 has two parents)
[[1,2],[2,3],[3,4],[4,1],[1,5]] → [4,1] (a cycle, nobody has two parents)
[[2,1],[3,1],[4,2],[1,4]] → [2,1] (two parents AND a cycle)Hints
- The extra edge either gives some node two parents, or creates a cycle back to the root, or both.
- If some node has two parent edges
cand1(earlier) andcand2(later): try deletingcand2. If the rest has no cycle,cand2is the answer, otherwise it'scand1.
Approach
- Scan for a node with two incoming edges. Call them
cand1(first) andcand2(second). - Run Union-Find over all edges except
cand2(if it exists):- If a cycle appears (an edge joins two nodes already connected):
- If there's no candidate pair, this edge is the answer (plain-cycle case, the last cycle edge found).
- Otherwise the answer is
cand1. Removingcand2didn't help, socand1lies on the cycle.
- If there's no cycle, the answer is
cand2.
- If a cycle appears (an edge joins two nodes already connected):
This covers all three cases with one pass of Union-Find. O(n · α(n)). The undirected version, Redundant Connection (LC 684), is just step 2 without the candidates.
Complexity
Time: O(n · α(n)). Space: O(n).
Python solution
def findRedundantDirectedConnection(edges):
n = len(edges)
parent_of = [0] * (n + 1)
cand1 = cand2 = None
for u, v in edges:
if parent_of[v]:
cand1, cand2 = [parent_of[v], v], [u, v]
else:
parent_of[v] = u
uf = list(range(n + 1))
def find(x):
while uf[x] != x:
uf[x] = uf[uf[x]]
x = uf[x]
return x
for u, v in edges:
if [u, v] == cand2:
continue
ru, rv = find(u), find(v)
if ru == rv:
return cand1 if cand1 else [u, v]
uf[rv] = ru
return cand2JavaScript solution
function findRedundantDirectedConnection(edges) {
const n = edges.length, parentOf = new Array(n + 1).fill(0);
let cand1 = null, cand2 = null;
for (const [u, v] of edges) {
if (parentOf[v]) { cand1 = [parentOf[v], v]; cand2 = [u, v]; }
else parentOf[v] = u;
}
const uf = [...Array(n + 1).keys()];
const find = (x) => { while (uf[x] !== x) { uf[x] = uf[uf[x]]; x = uf[x]; } return x; };
for (const [u, v] of edges) {
if (cand2 && u === cand2[0] && v === cand2[1]) continue;
const ru = find(u), rv = find(v);
if (ru === rv) return cand1 ? cand1 : [u, v];
uf[rv] = ru;
}
return cand2;
}