VOOZH about

URL: https://www.geeksforgeeks.org/dsa/gcd-traversal/

⇱ GCD Traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

GCD Traversal

Last Updated : 23 Jul, 2025

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:

  • Disjoint Set Union (Union-Find): The findParent and uniteSets functions implement the Union-Find data structure. This structure is used to efficiently determine the connectivity of elements in a set.
  • The canTraverseAllPairs function iterates through the elements of the nums vector.
  • It then uses the Union-Find operations (findParent and uniteSets) to merge sets of indices that share common prime factors. The factorsMap is used to keep track of the indices associated with each prime factor.
  • Check Final Connectivity: After processing all elements, the function checks whether all elements are part of a single connected component in the Union-Find structure. This is done by checking the size of the set containing the representative of the first element (0).

Below is the code for the above approach:


Output
1

Time complexity: O(sqrt(M) * N) where M is the largest number
Auxiliary space: O(N)

Comment