684. Redundant Connection
Problem
A tree with nodes 1…n had one extra edge added, creating a cycle. Given the edges, return an edge whose removal leaves a tree; if several qualify, return the one that appears last in the input.
Example: [[1,2],[1,3],[2,3]] → [2,3]
Constraints: 3 ≤ n ≤ 1000.
Process edges in order with Union-Find; the first edge whose endpoints are already connected closes a cycle → return it.
Complexity: O(E · α(V)).
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
parent = list(range(len(edges) + 1))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb:
return [a, b]
parent[ra] = rb
return []
assert Solution().findRedundantConnection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
assert Solution().findRedundantConnection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4]
class Solution {
private int[] parent;
private int find(int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
public int[] findRedundantConnection(int[][] edges) {
parent = new int[edges.length + 1];
for (int i = 0; i < parent.length; i++) parent[i] = i;
for (int[] e : edges) {
int ra = find(e[0]), rb = find(e[1]);
if (ra == rb) return e;
parent[ra] = rb;
}
return new int[0];
}
}
func findRedundantConnection(edges [][]int) []int {
parent := make([]int, len(edges)+1)
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]] // path halving
x = parent[x]
}
return x
}
for _, e := range edges {
ra, rb := find(e[0]), find(e[1])
if ra == rb { // already connected: this edge closes the cycle
return e
}
parent[ra] = rb
}
return nil
}