#Problem

#⭐️⭐️⭐️

Redundant Connection on undirected graph

#Solution

Union Find

#Performance

O(N * log(N)) time
O(N) space

#Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
private class UnionFind {
final int n;
final int[] id;
final int[] size;
UnionFind(final int n) {
this.n = n;
this.id = new int[n + 1];
this.size = new int[n + 1];
for (int i = 1; i <= n; i++) {
id[i] = i;
}
}
int root(final int v) {
int i = v;
while(id[i] != i) {
id[i] = id[id[i]];
i = id[i];
}
return i;
}
boolean find(final int v, final int w) {
return root(v) == root(w);
}
void union(final int v, final int w) {
final int rootV = root(v);
final int rootW = root(w);
if (size[rootV] > size[rootW]) {
id[rootW] = rootV;
size[rootV] += size[rootW];
} else {
id[rootV] = rootW;
size[rootW] += size[rootV];
}
}
}
public int[] findRedundantConnection(int[][] edges) {
final int n = edges.length;
final UnionFind uf = new UnionFind(n);
int[] res = null;
for (final int[] edge : edges) {
if (uf.find(edge[0], edge[1])) {
res = edge;
} else {
uf.union(edge[0], edge[1]);
}
}
return res;
}
}

Comments