Union Find Template (union by rank + path compression). Both techniques are used to optimize find method.
The below implementation is from LC disjoint set tutorial.

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
// UnionFind.class
class UnionFind {
private int[] root;
// Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex.
private int[] rank;

public UnionFind(int size) {
root = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) {
root[i] = i;
rank[i] = 1; // The initial "rank" of each vertex is 1, because each of them is
// a standalone vertex with no connection to other vertices.
}
}

// The find function here is the same as that in the disjoint set with path compression.
// Its function is to return the root of a given node.
public int find(int x) {
if (x == root[x]) {
return x;
}
return root[x] = find(root[x]);
}

// The union function with union by rank
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
root[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
root[rootX] = rootY;
} else {
root[rootY] = rootX;
rank[rootX] += 1;
}
}
}

public boolean connected(int x, int y) {
return find(x) == find(y);
}
}

Below is my version of union find. Should remember, memorize it and use it directly and comfortably.
The below implementation is from LC 547. Number of Provinces, which is a classic Union Find problem.

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
private static class UnionFind {
private int[] cityParent;
private int[] rank;
private int count;

private UnionFind(int size) {
cityParent = new int[size + 1];
rank = new int[size + 1];
for (int i = 1; i < cityParent.length; i++) {
cityParent[i] = i;
rank[i] = 1;
}
count = size;
}

private int find(int city) {
if (city == cityParent[city]) {
return city;
}
return cityParent[city] = find(cityParent[city]);
}

private void union(int city1, int city2) {
int city1Root = find(city1);
int city2Root = find(city2);
if (city1Root != city2Root) {
if (rank[city1Root] < rank[city2Root]) {
cityParent[city1Root] = city2Root;
} else if (rank[city1Root] > rank[city2Root]) {
cityParent[city2Root] = city1Root;
} else {
cityParent[city2Root] = city1Root;
rank[city1Root] += 1;
}
count -= 1;
}
}

private int getCount() {
return count;
}
}