Menu
CoddyTech

Redundant Connection

A network started as a tree: n nodes, numbered from 1 to n, joined by n-1 undirected edges with no cycle. Then one more edge was added between two nodes that were not directly joined, so the list edges now holds n edges and exactly one cycle.

Return an edge you can remove so that the other n-1 edges form a tree again. If several edges work, return the one that appears last in edges, as the pair [a, b] exactly as it is written there.

Function

findRedundantConnection(edges: integer-2d-array) → integer-array
edgesinteger-2d-array
the n undirected edges, each a pair [a, b] of nodes numbered from 1
Returnsinteger-array
the cycle edge that appears last in edges, written as it is there

Constraints

  • 3 ≤ n ≤ 5000, where n = edges.length
  • edges[i] = [a, b] with 1 ≤ a, b ≤ n and a ≠ b
  • No edge appears twice, in either direction.
  • The edges connect all n nodes and hold exactly one cycle.

Examples

Input
edges = [[1, 2], [1, 3], [2, 3]]
Output
[2, 3]
Explanation
The three edges form the triangle 1, 2, 3, so removing any one of them leaves a tree. [2, 3] comes last in the list.
challenge icon

Follow-up

If the edges were directed and the original graph a rooted tree, which edge would you remove when the extra edge gives a node two parents?

Reset code
def findRedundantConnection(edges):
    # Write code here

Test #1

Test #2

Argument

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

Expected Output

[2, 3]