Class Solution
-
- All Implemented Interfaces:
public final class Solution2709 - Greatest Common Divisor Traversal.
Hard
You are given a 0-indexed integer array
nums, and you are allowed to traverse between its indices. You can traverse between indexiand indexj,i != j, if and only ifgcd(nums[i], nums[j]) > 1, wheregcdis the greatest common divisor.Your task is to determine if for every pair of indices
iandjin nums, wherei < j, there exists a sequence of traversals that can take us fromitoj.Return
trueif it is possible to traverse between all such pairs of indices, orfalseotherwise.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(nums0, nums2) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums2, nums1) = gcd(6, 3) = 3 > 1. To go from index 0 to index 2, we can just go directly because gcd(nums0, nums2) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums1, nums2) = 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:
<code>1 <= nums.length <= 10<sup>5</sup></code>
<code>1 <= numsi<= 10<sup>5</sup></code>
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final BooleancanTraverseAllPairs(IntArray nums)-
-
Method Detail
-
canTraverseAllPairs
final Boolean canTraverseAllPairs(IntArray nums)
-
-
-
-