![]() |
VOOZH | about |
Given array nums, 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.
Examples:
Input: nums = [4,3,12,8] N=4
Output: true (1)
Explanation: Possible pairs: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). Sequence exists for each pair, so we return true.Input: nums = [3,9,5] N=3
Output: false (0)
Explanation: No sequence of traversals from 0 to 2. So, we return false.
Approach: To solve the problem follow the below idea:
The approach used for GCD traversal is Union-Find.
Steps to solve the problem:
Below is the code for the above approach:
1
Time complexity: O(sqrt(M) * N) where M is the largest number
Auxiliary space: O(N)