LeetCode 2709, Hard. Topics: Array, Math, Union Find, Number Theory. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:
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
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode 250, NeetCode All. Last modified on September 7, 2026