MediumDepth-First SearchBreadth-First SearchUnion FindGraph

1 approach, code in every language

Problem description

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.

After the pattern

Now solve one you haven't seen.

Surplus Irrigation Link is our own problem on the technique behind Redundant Connection: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free