Union Find and Prime Factorization

952. Largest Component Size by Common Factor

Union Find is a natural way to combine different sets with connection into one set. So the basic idea is:

  • If two numbers have common factor, union them
  • During the union process, maintain a set size as the final answer is asking for the set size.

Plain solution

class UF{
public:
vector<int> roots;
vector<int> sizes;
UF(int n){
roots.assign(n, 0); for (int i = 0; i < n; ++i)roots[i] = i;
sizes.assign(n, 1);

Speed up by using Prime Factorization

For example, for the number 8 and 12, the have the common factor of

{2, 4}, actually if they have the common prime factor will be enough as non prime factor can be further split to prime factors. In this example, 4 can be split to 2 * 2. So instead of using all factors, we can only use the prime factor to build the connection. For prime factorization, I borrowed it from [1].

class UF{
public:
vector<int> roots;
vector<int> sizes;
UF(int n){
roots.assign(n, 0); for (int i = 0; i < n; ++i)roots[i] = i;
sizes.assign(n, 1);

}
int find_set(int x){
return x == roots[x]? x: roots[x] = find_set(roots[x]);
}
void union_set(int x, int y){
int root_x = find_set(x), root_y = find_set(y);
if (root_x == root_y)return;
sizes[root_x] += sizes[root_y];
roots[root_y] = root_x;
}
int get_set_size(int x){
return sizes[x];
}
};

Run time

Time difference Top submission is the plain version and the bottom one is using the Prime Factorization version

Reference

[1] https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/