Redundant Connection

Medium#684

A tree on vertices 1 to n got one extra edge, so the graph now has exactly one cycle. You get its n edges. Return an edge that can be removed so that a tree is left; if several fit, the one that comes last in the list. Our example: [1, 2], [3, 4], [2, 4], [3, 1], [4, 5] → [3, 1].

input
edges: the n edges of an undirected graph on the vertices 1 to n, each [a, b] joining a and b. It is a tree with one edge added, so it has exactly one cycle.
returns
An edge whose removal leaves a tree on all n vertices, as it is written in edges. If several do, the one that comes last in edges.
constraints
  • n = edges.length, 3 ≤ n ≤ 400
  • edges[i] = [a, b], 1 ≤ a, b ≤ n, a ≠ b
  • no edge is given twice, either way round
  • the edges join all n vertices
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} edges
 * @return {number[]}
 */
function findRedundantConnection(edges) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more union-find problems

Pattern “Union-Find” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.