#2709
Greatest Common Divisor Traversal
HardArrayMathUnion-FindNumber TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max(nums))) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log(max(nums)))Space O(n)
Instead of checking all pairs, we can use a union-find (disjoint set) structure to efficiently group indices based on their GCD connections. This allows us to determine if all indices are connected in one pass.
⚙️
Algorithm
3 steps- 1Step 1: Create a union-find structure to manage connected components.
- 2Step 2: For each number, find its prime factors and union all indices that share a prime factor.
- 3Step 3: After processing all numbers, check if all indices belong to the same component.
solution.py49 lines
1# Full working Python code
2from collections import defaultdict
3
4class UnionFind:
5 def __init__(self, size):
6 self.parent = list(range(size))
7 self.rank = [1] * size
8
9 def find(self, u):
10 if self.parent[u] != u:
11 self.parent[u] = self.find(self.parent[u])
12 return self.parent[u]
13
14 def union(self, u, v):
15 rootU = self.find(u)
16 rootV = self.find(v)
17 if rootU != rootV:
18 if self.rank[rootU] > self.rank[rootV]:
19 self.parent[rootV] = rootU
20 elif self.rank[rootU] < self.rank[rootV]:
21 self.parent[rootU] = rootV
22 else:
23 self.parent[rootV] = rootU
24 self.rank[rootU] += 1
25
26def canTraverse(nums):
27 n = len(nums)
28 uf = UnionFind(n)
29 prime_to_index = defaultdict(list)
30
31 for i in range(n):
32 num = nums[i]
33 for factor in range(2, int(num**0.5) + 1):
34 if num % factor == 0:
35 prime_to_index[factor].append(i)
36 while num % factor == 0:
37 num //= factor
38 if num > 1:
39 prime_to_index[num].append(i)
40
41 for indices in prime_to_index.values():
42 for j in range(1, len(indices)):
43 uf.union(indices[0], indices[j])
44
45 root = uf.find(0)
46 return all(uf.find(i) == root for i in range(n))
47
48# Example usage
49print(canTraverse([2, 3, 6])) # Output: Trueℹ
Complexity note: The time complexity is O(n log(max(nums))) due to the factorization process for each number. The space complexity is O(n) for the union-find structure.
- 1Using prime factors helps reduce the number of connections we need to check.
- 2Union-Find is effective for dynamic connectivity problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.