> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Greatest Common Divisor Traversal

> Tested Python solution for LeetCode 2709 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 2709, Hard. Topics: Array, Math, Union Find, Number Theory. [View on LeetCode](https://leetcode.com/problems/greatest-common-divisor-traversal/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2709   # by problem number
lcpy gen -s greatest_common_divisor_traversal   # by problem name
```

## 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.

### Examples

```
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.
```

```
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.
```

```
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 \<= 10^5
* 1 \<= nums\[i] \<= 10^5

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/greatest_common_divisor_traversal/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/greatest_common_divisor_traversal/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class UnionFind:
    def __init__(self, size: int) -> None:
        self.parent = list(range(size))
        self.rank = [0] * size
        self.components = size

    def find(self, node: int) -> int:
        while self.parent[node] != node:
            self.parent[node] = self.parent[self.parent[node]]
            node = self.parent[node]
        return node

    def union(self, left: int, right: int) -> None:
        root_left = self.find(left)
        root_right = self.find(right)
        if root_left == root_right:
            return
        if self.rank[root_left] < self.rank[root_right]:
            root_left, root_right = root_right, root_left
        self.parent[root_right] = root_left
        if self.rank[root_left] == self.rank[root_right]:
            self.rank[root_left] += 1
        self.components -= 1


class Solution:
    # Time: O(n * sqrt(m))
    # Space: O(n)
    def can_traverse_all_pairs(self, nums: list[int]) -> bool:
        n = len(nums)
        if n == 1:
            return True

        uf = UnionFind(n)
        prime_to_index: dict[int, int] = {}

        for index, value in enumerate(nums):
            if value == 1:
                return False
            for factor in self._prime_factors(value):
                if factor in prime_to_index:
                    uf.union(index, prime_to_index[factor])
                else:
                    prime_to_index[factor] = index

        return uf.components == 1

    @staticmethod
    def _prime_factors(value: int) -> set[int]:
        factors: set[int] = set()
        divisor = 2
        while divisor * divisor <= value:
            if value % divisor == 0:
                factors.add(divisor)
                while value % divisor == 0:
                    value //= divisor
            divisor += 1
        if value > 1:
            factors.add(value)
        return factors
```

## Complexity

| Time            | Space |
| --------------- | ----- |
| O(n \* sqrt(m)) | O(n)  |

## Tags

[NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
