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: true
💡 Note: gcd(2,6)=2>1 connects indices 0 and 2, and gcd(3,6)=3>1 connects indices 1 and 2. All indices are connected through the path 0↔2↔1, so we can traverse between all pairs.
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 - Union-Find Solution INPUT nums = [4, 3, 12, 8] 4 i=0 3 i=1 12 i=2 8 i=3 Prime Factors: 4 = 2 x 2 3 = 3 12 = 2 x 2 x 3 8 = 2 x 2 x 2 Connection Graph: 4 3 8 12 ALGORITHM STEPS 1 Prime Factorize Find primes for each num 2 Initialize Union-Find Each index is own parent 3 Union by Primes Connect indices sharing same prime factor 4 Check Connectivity All in one component? Union Operations: Prime 2: union(0,2,3) 4,12,8 share factor 2 Prime 3: union(1,2) 3,12 share factor 3 Result: All connected! FINAL RESULT All indices connected through shared primes 0 1 3 2 Output: true OK - All pairs can traverse! Key Insight: Two numbers can be connected if they share a common prime factor (GCD > 1). Use Union-Find: group indices by their prime factors. If all indices end up in one connected component, every pair is reachable. Time: O(n * sqrt(max)) for factorization. TutorialsPoint - Greatest Common Divisor Traversal | Union-Find with Prime Factorization
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