Practice · Union-find · 2 of 2

The Extra Edge

A tree with n nodes, numbered from 1 to n, had one extra edge added between two of its nodes that weren't already joined directly. You are given the n edges of the result, edges, where each [a, b] (with a < b) joins nodes a and b. Edges have no direction.

Return an edge you can remove so that the remaining edges form a tree again: connected, with no cycle. If several edges would work, return the one that comes last in edges.

Example 1

Input
edges = [[1, 4], [3, 4], [1, 3], [1, 2], [4, 5]]
Output
[1, 3]
Nodes 1, 3 and 4 form a loop. Removing any of its three edges leaves a tree, and [1, 3] is the last of them in the list.

Example 2

Input
edges = [[2, 3], [1, 2], [3, 5], [4, 5], [1, 5]]
Output
[1, 5]
The loop is 1–2–3–5–1, and [1, 5] closes it last.

Constraints

  • 3 ≤ n ≤ 1000
  • edges holds exactly n edges, each [a, b] with 1 ≤ a < b ≤ n, and no edge appears twice.
  • The edges connect all n nodes.
Brush up firstUnion-Find visualiser