Greatest Common Divisor Traversal - Problem

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.

Input & Output

Example 1 — Connected Through Shared Factors
$ Input: nums = [4,3,12,8]
Output: true
💡 Note: gcd(4,12)=4>1, gcd(12,3)=3>1, gcd(4,8)=4>1. All indices can be reached: 0↔2↔1 and 0↔3, so all pairs are traversable.
Example 2 — Disconnected Components
$ Input: nums = [2,3,6]
Output: false
💡 Note: gcd(2,6)=2>1 connects indices 0 and 2, but gcd(3,2)=1 and gcd(3,6)=3>1. Index 1 connects to 2 but not 0, so we can't traverse from 0 to 1.
Example 3 — Single Element
$ Input: nums = [7]
Output: true
💡 Note: With only one element, there are no pairs to check, so the answer is trivially true.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
GCD Traversal: Can We Reach All Indices?43128index 0index 1index 2index 3gcd(4,12)=4gcd(3,12)=3gcd(4,8)=4All indices connected through shared prime factorsResult: true
Understanding the Visualization
1
Input Array
Array of integers with their indices
2
GCD Connections
Find which pairs have GCD > 1
3
Check Connectivity
Determine if all indices are reachable
Key Takeaway
🎯 Key Insight: Use prime factorization and Union-Find to efficiently check if all indices are in the same connected component
Asked in
Google 25 Facebook 20 Microsoft 15
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen