0685. Redundant Connection II
https://leetcode.com/problems/redundant-connection-ii
Description
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 [ui, vi]
that represents a directed edge connecting nodes ui
and vi
, where ui
is a parent of child vi
.
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.
Example 1:

**Input:** edges = [[1,2],[1,3],[2,3]]
**Output:** [2,3]
Example 2:

**Input:** edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
**Output:** [4,1]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
ac
class Solution {
public int[] findRedundantDirectedConnection(int[][] edges) {
// edge cases
int n = edges.length;
int[] fathers = new int[n+1];
int[] candi1 = null, candi2 = null;
// find 2 candidates if exist
for (int[] e : edges) {
if (fathers[e[1]] != 0) { // e[1] has parent already
candi1 = new int[]{fathers[e[1]], e[1]};
candi2 = new int[]{e[0], e[1]};
e[1] = 0; // set 2nd candidate invalid
} else { // set fathers to represent direction
fathers[e[1]] = e[0];
}
}
// build union find
for (int i = 0; i < fathers.length; i++) fathers[i] = i; // reset
for (int[] e : edges) {
int f1 = find(fathers, e[0]);
int f2 = find(fathers, e[1]);
if (f1 != f2) { // normal connect
fathers[f1] = f2;
} else { // find cycle
if (candi1 == null) return e; // 1 parent
else return candi1; // 2 parent
}
}
return candi2;
}
private int find(int[] fathers, int i) {
int res = i;
while (fathers[res] != res) {
res = fathers[res];
}
return res;
}
}
/*
3 situations: loop 1 find 2 candidates -> union find -> 1) no cycle, return 2nd candidate; 2) cycle, 1 parent, return current edge; 3) cycle, 2 parent, return 1st candidate.
*/
Last updated
Was this helpful?