Redundant Connection

Graphs, problem 6 of 8

Redundant Connection

Medium

LC #684

union-findcycle detection

Not attempted yet

A tree with n nodes (labelled 1..n) had one extra edge added, so the undirected graph given as edges now contains exactly one cycle.

Return an edge you can remove so the graph becomes a tree again. If several edges qualify, return the one that appears last in edges.

Example 1

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

Example 2

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

The cycle is 1-2-3-4-1; [1,4] is its last edge in the input.

Constraints

  • 3 <= n <= 2 * 10^4, len(edges) == n
  • 1 <= a < b <= n for each edge [a, b], no duplicates
  • the graph is connected

Python

Loading draft…

Test results

7 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

2 examples, 5 hidden

Run examples, then submit all tests.