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.
// UnionFind.class classUnionFind { privateint[] root; // Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex. privateint[] rank;
publicUnionFind(int size) { root = newint[size]; rank = newint[size]; for (inti=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. publicintfind(int x) { if (x == root[x]) { return x; } return root[x] = find(root[x]); }
// The union function with union by rank publicvoidunion(int x, int y) { introotX= find(x); introotY= find(y); if (rootX != rootY) { if (rank[rootX] > rank[rootY]) { root[rootY] = rootX; } elseif (rank[rootX] < rank[rootY]) { root[rootX] = rootY; } else { root[rootY] = rootX; rank[rootX] += 1; } } }
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.