↓Skip to main content
  1. LeetCode/

LeetCode 2709: Greatest Common Divisor Traversal

·3 mins· ·
LeetCode Hard Math Number-Theory Union-Find Sieve Gcd Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2025-08-07

  • Submissions: TLE → RE → WA ×2 → TLE ×2 (2025-08-07) → AC → WA → RE → AC (2026-10-12)

Approach
#

“Every pair of indices can reach each other” ⇔ all indices form one component. As in LeetCode 952, prime factors replace pairwise GCDs.

Here the Union-Find nodes are values: sieve SPF up to max(nums) and union every number with each of its prime factors. Finally check that all numbers share one root.

The special case of 1: 1 has no prime factors and connects to nothing.

  • With a single element there is no pair to check, so the answer is True (even for [1]).
  • With more than one element and any 1: always False.

My Attempts
#

VersionProblem
Attempt 1, TLEPairwise GCDs, O(n^2)
RETried to deduplicate with nums = set(nums), but a set cannot be indexed
WADeduplicated with list(set(nums)), collapsing two 1s into one. For [1, 1] the two 1s cannot reach each other, so the answer is False; it returned True
WAAdded “any 1 means False”, but [1] alone is True
Two TLEsStill pairwise GCDs
AC (a year later)Unioned indices by prime factor
WASwitched to SPF with values as nodes, again without handling 1: [1, 1] returned True
REAdded an n == 1 check, but before n = len(nums)
ACReordered

Solution
#

class Solution:
    def canTraverseAllPairs(self, nums: List[int]) -> bool:
        n = len(nums)
        if n == 1:
            return True
        if 1 in nums:
            return False                           # 1 connects to nothing

        m = max(nums)
        spf = list(range(m + 1))
        for i in range(2, int(m ** 0.5) + 1):
            if spf[i] == i:
                for j in range(i * i, m + 1, i):
                    if spf[j] == j:
                        spf[j] = i

        parent = list(range(m + 1))                # nodes are values

        def find(a: int) -> int:
            while parent[a] != a:
                parent[a] = parent[parent[a]]
                a = parent[a]
            return a

        for x in nums:
            v = x
            while v > 1:
                p = spf[v]
                parent[find(x)] = find(p)          # union the number with its prime factor
                while v % p == 0:
                    v //= p

        root = find(nums[0])
        return all(find(x) == root for x in nums)

Complexity
#

Time O(M log log M + n log M) with M the maximum; space O(M).

Mistakes to Avoid
#

  • Pairwise GCDs: O(n^2).
  • Deduplicating: two equal 1s are two indices, and deduplication merges them.
  • [1] is True; only with more than one element does a 1 mean False.

Interview Explanation
#

Every pair connecting means everything is one component. Sharing a factor means sharing a prime factor, so I factor each number with an SPF sieve, union each number with its prime factors in Union-Find, and check that all numbers share a root. 1 has no prime factors: a single element is True, otherwise any 1 means False.

Related

LeetCode 952: Largest Component Size by Common Factor
·2 mins
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
LeetCode 952 note: sharing a factor ⇔ sharing a prime factor; factor each number and union indices with the same prime factor using Union-Find, with no pairwise GCDs
LeetCode 3618: Split Array by Prime Indices
·2 mins
LeetCode Medium Math Number-Theory Sieve Array
LeetCode 3618 note: primality is about the index; a sieve of Eratosthenes marks all of 0..n-1 at once, faster than trial division per index
LeetCode 1979: Find Greatest Common Divisor of Array
·1 min
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 note: find the minimum and maximum, then take their GCD with Euclid’s algorithm
LeetCode 927: Three Equal Parts
·3 mins
LeetCode Hard Math Array
LeetCode 927 note: every part has the same number of 1s, so count them; the third part always runs to the end of the array, fixing what each part must match, then check the parts do not overlap
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 135: Candy
·2 mins
LeetCode Hard Greedy Array
LeetCode 135 note: one pass left to right for the left neighbor, one right to left for the right neighbor, and give each child the larger of the two