Union-find
Time O(n α(n)) Space O(n)Union edges in order; return the first edge with both ends in the same set. It's the last edge of the only cycle in input order.
class Solution {
private int[] parent;
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 a = find(e[0]), b = find(e[1]);
if (a == b) return e;
parent[a] = b;
}
return new int[0];
}
private int find(int x) {
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
}Verdict: Exactly the cycle check from the lesson.