MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Redundant Connection

LeetCode
1 approach, code in all languages

You start with a tree that has n nodes labeled from 1 to n, meaning it is connected and contains no cycles. Someone then adds exactly one extra edge between two distinct nodes that were already in the tree, creating a graph with n edges and exactly one cycle.

You are given the resulting edges as a list, where edges[i] = [a, b] indicates an undirected edge between nodes a and b. Return an edge that can be removed so the remaining graph is again a tree of n nodes.

If several answers exist, return the edge that appears last in the input.

Example 1

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

Output: [2,3]

Edges [1,2] and [1,3] already connect all three nodes; adding [2,3] closes a cycle, so removing it restores a tree.

Example 2

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

Output: [1,4]

By the time [1,4] is processed, nodes 1 and 4 are already connected through 1-2-3-4, so [1,4] is the redundant edge.

Constraints

  • n == edges.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= a_i < b_i <= edges.length
  • a_i != b_i
  • There are no repeated edges.
  • The given graph is connected.
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