SDE & MLE Prep

2709. Greatest Common Divisor Traversal

Problem

You can move between indices i and j of nums if gcd(nums[i], nums[j]) > 1. Decide whether every pair of indices is connected by some sequence of such moves.

Example: [2,3,6] → true; [3,9,5] → false

Constraints: n ≤ 10⁵; values ≤ 10⁵.

Indices i and j are directly connected iff they share a prime factor, so connect each index to its primes: with a smallest-prime-factor sieve, factor every number and union the index with the first index seen for each of its primes. Traversal between all pairs ⇔ one connected component. A 1 (no prime factors) is isolated unless it's the only element.

Complexity: O(M log log M + n log M) for M = max(nums).

class Solution:
    def canTraverseAllPairs(self, nums: List[int]) -> bool:
        n = len(nums)
        if n == 1:
            return True
        if 1 in nums:
            return False
        M = max(nums)
        spf = list(range(M + 1))                      # smallest prime factor
        for i in range(2, int(M ** 0.5) + 1):
            if spf[i] == i:
                for j in range(i * i, M + 1, i):
                    if spf[j] == j:
                        spf[j] = i
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        first = {}                                    # prime -> first index having it
        for i, x in enumerate(nums):
            while x > 1:
                p = spf[x]
                if p in first:
                    parent[find(i)] = find(first[p])
                else:
                    first[p] = i
                while x % p == 0:
                    x //= p
        return len({find(i) for i in range(n)}) == 1