##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/685.html

# 685. Redundant Connection II

Hard

## 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 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.

Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v   v
2-->3


Example 2:

Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^    |
|    v
4 <- 3


Note:

• The size of the input 2D-array will be between 3 and 1000.
• Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.

## Solution

If a connection is redundant, there may be two cases. The first case is that the connection causes a conflict, which means a node has more than one parent. The second case is that the connection introduces a cycle.

Maintain a global variable parents which is an array to store each node’s parent node. The number of nodes equals edges.length. Initialize parents[i] = i for each node i.

Loop over edges. For each edge in edges, if parent[edge] != edge, then edge is already a child of another node, so edge introduces a conflict, and store the current edge’s index as the conflict index. Otherwise, if neither a conflict connection nor a cycle connection is found, find the ancestors of edge and edge. If the two nodes’ ancestors are the same, then edge introduces a cycle, and store the current edge’s index as the cycle index.

If no conflict is found, then return the connection at the cycle index.

If there is a conflict found, then check whether the connection at the conflict index causes a cycle. If so, return the connection at the conflict index. Otherwise, return the other connection that has the same child as the connection at the conflict index.

• class Solution {
int[] parents;

public int[] findRedundantDirectedConnection(int[][] edges) {
int nodesCount = edges.length;
parents = new int[nodesCount + 1];
for (int i = 1; i <= nodesCount; i++)
parents[i] = i;
int conflict = -1;
int cycle = -1;
for (int i = 0; i < nodesCount; i++) {
int[] edge = edges[i];
int node1 = edge, node2 = edge;
if (parents[node2] != node2)
conflict = i;
else {
if (conflict < 0 && cycle < 0) {
int ancestor1 = findAncestor(node1);
int ancestor2 = findAncestor(node2);
if (ancestor1 == ancestor2)
cycle = i;
}
parents[node2] = node1;
}
}
if (conflict < 0) {
int[] redundant = {edges[cycle], edges[cycle]};
return redundant;
}
int[] conflictEdge = edges[conflict];
if (containsCycle(conflictEdge)) {
int[] redundant = new int;
redundant = conflictEdge;
redundant = parents[conflictEdge];
return redundant;
} else {
int[] redundant = {conflictEdge, conflictEdge};
return redundant;
}
}

public boolean containsCycle(int node) {
int tempNode = node;
while (parents[node] != node) {
if (parents[node] == tempNode)
return true;
node = parents[node];
}
return false;
}

public int findAncestor(int node) {
while (parents[node] != node)
node = parents[node];
return node;
}
}

• // OJ: https://leetcode.com/problems/redundant-connection-ii/
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& E) {
int N = E.size(), terminal = -1;
vector<vector<pair<int, int>>> G(N);
vector<vector<pair<int, int>>> R(N);
vector<bool> onCycle(N, true);
vector<int> indegree(N), outdegree(N);
for (int i = 0; i < N; ++i) {
int u = E[i] - 1, v = E[i] - 1;
G[u].push_back({v,i});
R[v].push_back({u,i});
if (++indegree[v] == 2) terminal = v;
++outdegree[u];
}
auto hasCycle = [&]() { // Topological sort to see if there is any cycle in the graph
queue<int> q;
int seen = 0;
for (int i = 0; i < N; ++i) {
if (indegree[i] == 0) q.push(i);
}
while (q.size()) {
int u = q.front();
onCycle[u] = false;
++seen;
q.pop();
for (auto &[v, i] : G[u]) {
if (--indegree[v] == 0) q.push(v);
}
}
return seen < N;
};
if (hasCycle()) {
if (terminal != -1) { // case 1
int a = R[terminal].first, b = R[terminal].first;
if (onCycle[a]) return {a + 1, terminal + 1};
return {b + 1, terminal + 1};
}
queue<int> q; // case 3
for (int i = 0; i < N; ++i) {
if (outdegree[i] == 0) q.push(i);
}
while (q.size()) {
int u = q.front();
q.pop();
onCycle[u] = false; // Topological Sort on the reversed graph to remove nodes that are not on the cycle.
for (auto &[v, i] : R[u]) {
if (--outdegree[v] == 0) q.push(v);
}
}
int ans = -1;
for (int i = 0; i < N; ++i) {
if (!onCycle[i]) continue;
for (auto &[v, j] : R[i]) {
ans = max(ans, j); // Find the greatest edge index on the cycle
}
}
return E[ans];
}
return {R[terminal].first + 1, terminal + 1}; // case 2
}
};

• class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.n = n

def union(self, a, b):
if self.find(a) == self.find(b):
return False
self.p[self.find(a)] = self.find(b)
self.n -= 1
return True

def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]

class Solution:
def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
n = len(edges)
p = list(range(n + 1))
uf = UnionFind(n + 1)
conflict = cycle = None
for i, (u, v) in enumerate(edges):
if p[v] != v:
conflict = i
else:
p[v] = u
if not uf.union(u, v):
cycle = i
if conflict is None:
return edges[cycle]
v = edges[conflict]
if cycle is not None:
return [p[v], v]
return edges[conflict]


• type unionFind struct {
p []int
n int
}

func newUnionFind(n int) *unionFind {
p := make([]int, n)
for i := range p {
p[i] = i
}
return &unionFind{p, n}
}

func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}

func (uf *unionFind) union(a, b int) bool {
if uf.find(a) == uf.find(b) {
return false
}
uf.p[uf.find(a)] = uf.find(b)
uf.n--
return true
}

func findRedundantDirectedConnection(edges [][]int) []int {
n := len(edges)
p := make([]int, n+1)
for i := range p {
p[i] = i
}
uf := newUnionFind(n + 1)
conflict, cycle := -1, -1
for i, e := range edges {
u, v := e, e
if p[v] != v {
conflict = i
} else {
p[v] = u
if !uf.union(u, v) {
cycle = i
}
}
}
if conflict == -1 {
return edges[cycle]
}
v := edges[conflict]
if cycle != -1 {
return []int{p[v], v}
}
return edges[conflict]
}