Problem solution · C++

Greatest Common Divisor Traversal

Greatest Common Divisor Traversal: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
82 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Greatest Common Divisor Traversal, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 82 lines of C++ from the credited upstream file 2709.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 7 loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeGreatest Common Divisor Traversal · C++C++
Use this to learn the idea, then write your own version.
class UnionFind { public:  UnionFind(int n) : id(n), sz(n, 1) {    iota(id.begin(), id.end(), 0);  }   void unionBySize(int u, int v) {    const int i = find(u);    const int j = find(v);    if (i == j)      return;    if (sz[i] < sz[j]) {      sz[j] += sz[i];      id[i] = j;    } else {      sz[i] += sz[j];      id[j] = i;    }  }   int getSize(int i) {    return sz[i];  }  private:  vector<int> id;  vector<int> sz;   int find(int u) {    return id[u] == u ? u : id[u] = find(id[u]);  }}; class Solution { public:  bool canTraverseAllPairs(vector<int>& nums) {    const int n = nums.size();    const int mx = ranges::max(nums);    const vector<int> minPrimeFactors = sieveEratosthenes(mx + 1);    unordered_map<int, int> primeToFirstIndex;    UnionFind uf(n);     for (int i = 0; i < n; ++i)      for (const int primeFactor : getPrimeFactors(nums[i], minPrimeFactors))        // `primeFactor` already appeared in the previous indices.        if (const auto it = primeToFirstIndex.find(primeFactor);            it != primeToFirstIndex.cend())          uf.unionBySize(it->second, i);        else          primeToFirstIndex[primeFactor] = i;     for (int i = 0; i < n; ++i)      if (uf.getSize(i) == n)        return true;     return false;  }  private:  // Gets the minimum prime factor of i, where 1 < i <= n.  vector<int> sieveEratosthenes(int n) {    vector<int> minPrimeFactors(n + 1);    iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);    for (int i = 2; i * i < n; ++i)      if (minPrimeFactors[i] == i)  // `i` is prime.        for (int j = i * i; j < n; j += i)          minPrimeFactors[j] = min(minPrimeFactors[j], i);    return minPrimeFactors;  }   vector<int> getPrimeFactors(int num, const vector<int>& minPrimeFactors) {    vector<int> primeFactors;    while (num > 1) {      const int divisor = minPrimeFactors[num];      primeFactors.push_back(divisor);      while (num % divisor == 0)        num /= divisor;    }    return primeFactors;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗