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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code