Graphs Union-find
470. Redundant Connection II
A rooted tree is a directed graph with one node, the root, that has no parent. Every other node has exactly one parent, and every node can be reached from the root by following edges from parent to child.
You are given a directed graph that started as a rooted tree on n nodes, numbered from 1 to n, and
then got one more edge. The new edge joins two different nodes, and the tree did not already have it.
The graph is given as edges, which has n rows. Each row [u, v] is an edge from u to v, so u is a
parent of v.
Return an edge whose removal leaves a rooted tree on all n nodes. If several edges would do, return the
one that comes last in edges.
Example 1
Input: edges = [[2, 3], [3, 4], [4, 2], [1, 2]]
[4,2]Explanation: Node 2 has two parents, 4 and 1. Removing [1,2] would leave the cycle 2 → 3 → 4 → 2 and cut node 1
off. Removing [4,2] leaves a tree rooted at 1.
Example 2
Input: edges = [[3, 1], [1, 2], [2, 3], [2, 4]]
[2,3]Explanation: Every node has one parent, and 1 → 2 → 3 → 1 is a cycle. Removing any edge of the cycle leaves a tree,
and [2,3] comes last of the three. Removing [2,4] would cut node 4 off.
Example 3
Input: edges = [[1, 2], [1, 3], [2, 3]]
[2,3]Explanation: Node 3 has two parents. Removing either edge into it leaves a tree rooted at 1, and [2,3] comes last.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
2 ≤ n ≤ 105, where n isedges.lengthedges[i].length == 21 ≤ ui, vi ≤ nandui ≠ vi- No edge appears twice.
- The graph is a rooted tree with one extra edge.
Clarifying questions
What you would ask an interviewer before writing any code.