Problem Description
Given an array of integers nums, determine if it is possible to traverse between every pair of indices with a sequence of steps such that for any direct step between indices i and j (i != j), the greatest common divisor (gcd) of nums[i] and nums[j] is greater than 1.
Key Insights
- The traversal can be modeled as a graph problem where each index is a node.
- An edge exists between index i and j if gcd(nums[i], nums[j]) > 1.
- Instead of checking pairwise gcd (which is too slow for large arrays), we can use prime factorization.
- Connect indices that share a common prime factor through union-find.
- Efficiently factorize numbers using a precomputed sieve or trial division since maximum nums[i] is 10^5.
Space and Time Complexity
Time Complexity: O(n * log(max(nums[i]))) on average due to factorization and union operations. Space Complexity: O(n + max(nums[i])) for storing union-find structures and prime factor mappings.
Solution
The idea is to view the problem as checking if the induced graph is fully connected. We will:
- Factorize each number in the array to get its distinct prime factors.
- For every prime factor, link all indices whose numbers contain that factor using a union-find (disjoint set union) data structure.
- After processing all numbers, verify that all indices belong to a single connected component.
Data Structures and Approaches:
- Use an efficient union-find implementation with path compression.
- Use a dictionary to map a prime factor to the first index encountered for that factor.
- For each subsequent number containing the same factor, union it with the stored index.
Key Gotchas:
- Make sure to only consider unique prime factors for each number (avoid duplicate unions).
- Factorization should be efficient to handle up to 10^5 elements.