Greatest Common Divisor Traversal Problem
Description
LeetCode Problem 2709.
You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor.
Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j.
Return true if it is possible to traverse between all such pairs of indices, or false otherwise.
Example 1:
Input: nums = [2,3,6]
Output: true
Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2).
To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1.
To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1.
Example 2:
Input: nums = [3,9,5]
Output: false
Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false.
Example 3:
Input: nums = [4,3,12,8]
Output: true
Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Union-Find over Prime Factors
Two indices can be connected when their numbers share a prime factor, so we link every index to each prime factor of its number. Use a union-find over n + m + 1 nodes: nodes 0..n-1 are the indices, and node n + p stands for the prime p (m is the largest number).
For each nums[i], factorize it by trial division and union i with every prime factor found. Two indices share a prime factor exactly when they end up in one component, so all pairs can traverse each other when all n indices have one common root.
A value of 1 has no prime factors, so it stays alone; this is correct because gcd(1, x) = 1 for every x. (With a single element the answer is true.)
Complexity: O(n sqrt(M) α) time and O(n + M) space, where M is the largest value. The inverse-Ackermann factor α is tiny.
from collections import defaultdict
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
mx = 100010
p = defaultdict(list)
for x in range(1, mx + 1):
v = x
i = 2
while i <= v // i:
if v % i == 0:
p[x].append(i)
while v % i == 0:
v //= i
i += 1
if v > 1:
p[x].append(v)
class Solution:
def canTraverseAllPairs(self, nums: List[int]) -> bool:
n = len(nums)
m = max(nums)
uf = UnionFind(n + m + 1)
for i, x in enumerate(nums):
for j in p[x]:
uf.union(i, j + n)
return len(set(uf.find(i) for i in range(n))) == 1