AceYourInterviews
Checking sign-in…

110. Redundant Connection

CoreFind the last input occurrence whose endpoints were already connected

Process the edges in order and identify edges whose endpoints are already connected by earlier edges. Return the last such edge under the extended course contract.

On the usual tree-plus-one-edge input, this selects the removable edge with the required input-order tie rule. Preserve the input and do not return an aliased input row.

Example 1

Input

[[1,2],[1,3],[2,3]]

Output

[2,3]

Explanation: Before the last edge, 2 and 3 already connect through 1.

Example 2

Input

[[1,2],[2,3],[3,1],[3,4],[4,1]]

Output

[4,1]

Explanation: Two different occurrences close cycles. Return the later one without claiming a single deletion repairs both cycles.

Example 3

Input

[[2,1],[1,2]]

Output

[1,2]

Explanation: The second occurrence is redundant even though its orientation differs from the first.

Example 4

Input

[[7,7]]

Output

[7,7]

Explanation: A vertex is already connected to itself; a self-loop is a cycle-closing occurrence.

Constraints

  • 0 <= edges.length <= 2 * 105
  • edges[i].length == 2
  • 1 <= vertex label <= 105
Hints
Hint 1

Before inserting an undirected edge, ask whether its endpoints are already connected.

Hint 2

A failed union records a cycle-closing occurrence; a successful union only joins components.

Hint 3

Keep the latest failed pair in a fresh array, preserving external labels and orientation.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

The last edge of a simple triangle closes the cycle

[[1,2],[1,3],[2,3]]
[2,3]