Redundant Connection II
1 approach, code in every language
Problem description
A rooted tree is a directed graph where exactly one node is the root (it has no incoming edge) and every other node has exactly one parent, so all edges point away from the root.
You start with such a rooted tree on n nodes labeled 1 to n and add exactly one extra directed edge, forming edges of length n where edges[i] = [u, v] represents a directed edge from u to v.
Return the one edge that can be removed so the remaining graph is a valid rooted tree again. If several edges qualify, return the one that appears last in the input.
Example 1
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Node 3 has two parents (1 and 2). Removing [2,3] leaves node 1 as the root with children 2 and 3, a valid tree.
Example 2
Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]
Every node has one parent but the edges 1 -> 2 -> 3 -> 4 -> 1 form a cycle. Removing [4,1] breaks the loop and restores a rooted tree.
Constraints
n == edges.length3 <= n <= 1000edges[i].length == 21 <= u_i, v_i <= nu_i != v_i
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free