HardDepth-First SearchBreadth-First SearchUnion FindGraph

Redundant Connection II

LeetCode
1 approach, code in all languages

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.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= u_i, v_i <= n
  • u_i != v_i
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now