Skip to main content

Greatest Common Divisor Traversal - Solution & Explanation

Practice this problem

Problem Statement

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.

 

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(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1.
To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = 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:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Approach Overview

Problem Overview: You receive an array of integers. You can move between two indices if the gcd(nums[i], nums[j]) > 1. The task is to determine whether every index can be reached from any starting index, meaning the implicit graph formed by these gcd relationships is fully connected.

Approach 1: Graph Traversal by Adjacency List (O(n² log M) time, O(n²) space)

Treat every number as a node in a graph. Compare every pair of values and compute gcd(nums[i], nums[j]). If the result is greater than 1, add an edge between the two indices in an adjacency list. After building the graph, run DFS or BFS to check whether all nodes are reachable from index 0. This approach directly models the graph but performs a gcd calculation for every pair, which becomes expensive for large arrays. It works well for small inputs or when building intuition around graph traversal.

Approach 2: Graph Traversal with Union-Find and Prime Factors (O(n log M) time, O(n + M) space)

Instead of comparing every pair, connect numbers through their prime factors. Factorize each value and track which indices share the same factor. If two numbers contain a common prime factor, union their indices using a Union-Find structure. A hash map from factor → index allows quick unions as factors repeat. This effectively builds the connectivity of the graph without enumerating all edges. Prime factorization takes roughly O(log M) per number using trial division or a smallest-prime-factor sieve from number theory. After processing the entire array, check whether all indices belong to the same set.

The key insight: if two numbers share any prime factor, their gcd is greater than 1, so they belong in the same connected component. Chaining these unions across shared factors builds the full connectivity of the array.

Recommended for interviews: The Union-Find with prime factorization approach. The adjacency-list solution shows you understand the graph model but fails to scale because of the O(n²) pair checks. Interviewers expect the optimized approach that reduces the problem to factor connectivity and merges components using disjoint sets.

Approach 1: Graph Traversal with Union-Find

This approach considers the integer array as a graph where each index is a node. We connect nodes i and j if gcd(nums[i], nums[j]) > 1. Using a union-find data structure, we efficiently manage connected components as we establish connections among indices. The goal is to determine whether all indices are part of a single connected component.

This C code uses the union-find algorithm to determine the connectivity of an array. We initialize unconnected components for each element, then iterate through the elements, connecting them if their GCD is greater than 1. If all elements share the same root parent after processing, they belong to a single connected component, implying that traversal is possible between every index.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity is O(n^2 * log*(n)), due to the nested for loops for each pair of numbers, where log* is the inverse Ackermann function that represents the amortized time of the union-find operations. The space complexity is O(n) for storing the union-find array.

Try this approach in the editor →

Approach 2: Graph Traversal by Adjacency List

In this approach, the solution represents the integer array as an adjacency list graph. Each index is considered as a node, and we link them with edges if their GCD is greater than 1. We perform a depth-first search (DFS) or breadth-first search (BFS) to determine the connectivity of the nodes. If all indices are reachable from any starting index, the traversal is possible.

This C code constructs a graph using an adjacency matrix. It uses DFS to check connectivity from the first index to all others, ensuring all indices are reachable.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity is O(n^2), and the space complexity also is O(n^2) due to the adjacency matrix representation.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Graph Traversal with Union-Find

The time complexity is O(n^2 * log*(n)), due to the nested for loops for each pair of numbers, where log* is the inverse Ackermann function that represents the amortized time of the union-find operations. The space complexity is O(n) for storing the union-find array.

Graph Traversal by Adjacency List

The time complexity is O(n^2), and the space complexity also is O(n^2) due to the adjacency matrix representation.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Adjacency List + DFS/BFSO(n² log M)O(n²)Small arrays or when demonstrating the direct graph interpretation
Union-Find with Prime FactorizationO(n log M)O(n + M)Large inputs and interview settings where optimal connectivity detection is required

Video Solution

Greatest Common Divisor Traversal - Leetcode 2709 - PythonNeetCodeIO14,707 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Greatest Common Divisor Traversal easy or hard?
Greatest Common Divisor Traversal is categorized as a Hard problem. The challenge comes from recognizing that pairwise gcd checks are too slow and transforming the problem into prime-factor connectivity solved with Union-Find.
Greatest Common Divisor Traversal Python/Java solution
Python and Java solutions typically implement a Union-Find class with path compression and union by rank. Each number is factorized, and indices sharing factors are merged in the same set. After processing all numbers, checking that all indices share the same root confirms full traversal.
How to solve Greatest Common Divisor Traversal in O(n)?
Pure O(n) is not typically achievable because each number must be factorized. The closest practical complexity is O(n log M) using prime factorization and Union-Find. Precomputing smallest prime factors with a sieve can make factorization extremely fast in practice.
What is the best approach for Greatest Common Divisor Traversal?
The most efficient approach uses Union-Find combined with prime factorization. Each number is broken into its prime factors, and indices sharing a factor are unioned in a disjoint set. This avoids comparing every pair of numbers and reduces the complexity to about O(n log M), where M is the maximum value in the array.
Is Greatest Common Divisor Traversal asked at Google/Amazon/Meta?
This style of problem frequently appears in interviews at companies like Google, Amazon, and Meta because it combines number theory with graph connectivity. Candidates are expected to recognize that shared prime factors create edges and solve it using Union-Find.
What data structure is used in Greatest Common Divisor Traversal?
The core data structure is Union-Find (Disjoint Set Union) to maintain connected components efficiently. A hash map or array is also used to track the first index seen for each prime factor during factorization.
What is the time complexity of Greatest Common Divisor Traversal?
The optimal solution runs in O(n log M) time due to prime factorization of each number and near-constant Union-Find operations with path compression. A naive adjacency graph approach that checks gcd for every pair costs O(n² log M), which becomes too slow for large inputs.

Ready to solve this problem?

Practice Greatest Common Divisor Traversal with our built-in code editor and test cases.

Practice on FleetCode