oneby7

Graphs Union-find

470. Redundant Connection II

Hard

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

1234

Input: edges = [[2, 3], [3, 4], [4, 2], [1, 2]]

Output: [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

1234

Input: edges = [[3, 1], [1, 2], [2, 3], [2, 4]]

Output: [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

123

Input: edges = [[1, 2], [1, 3], [2, 3]]

Output: [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.

edges = [[3, 1], [4, 1], [1, 2], [2, 3], [2, 5]]

Constraints

  • 2 ≤ n ≤ 105, where n is edges.length
  • edges[i].length == 2
  • 1 ≤ ui, vi ≤ n and ui ≠ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.