This page explains Java solution to problem `Redundant Connection II`

using `Union and Find`

algorithm.

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 `1, 2, ..., 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, v]`

that represents a directed edge connecting nodes `u`

and `v`

, where `u`

is a parent of child `v`

.

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: [[1,2], [1,3], [2,3]]Output: [2,3]

Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]Output: [4,1]

```
package com.vc.hard;
class RedundantConnectionIi {
public int[] findRedundantDirectedConnection(int[][] edges) {
int n = edges.length;
int[] parentArr = new int[n + 1];
for(int i = 0; i < parentArr.length; i++) parentArr[i] = i;
int[] cycleEdge = null;
int[] multipleParentEdge = null;
for(int[] edge: edges) {
int from = edge[0], to = edge[1];
int fromParent = find(from, parentArr);
int toParent = find(to, parentArr);
//If we find multipleParentEdge we don't add it to parentArr
if(toParent != to) multipleParentEdge = edge;
//If we find cycleEdge we don't add it to parentArr
else if(fromParent == toParent) cycleEdge = edge;
else parentArr[toParent] = fromParent;
}
if(multipleParentEdge == null) return cycleEdge;
if(cycleEdge == null) return multipleParentEdge;
//Now if we find both that means multipleParentEdge is not part of cycle,
//So there has to be another edge which will cause cycle and causing multipleParent
for(int[] edge: edges) {
if(edge[1] == multipleParentEdge[1]) return edge;
}
return multipleParentEdge; //won't reach here
}
private int find(int x, int[] parent) {
if(parent[x] == x) return x;
else return parent[x] = find(parent[x], parent);
}
}
```

O(N * log N) Where

N is total number of edges in an input array

O(N) Where

N is total number of edges in an input array