- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 61 lines of Python from the credited upstream file 2709.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind:2 def __init__(self, n: int):3 self.id = list(range(n))4 self.sz = [1] * n5 6 def unionBySize(self, u: int, v: int) -> None:7 i = self._find(u)8 j = self._find(v)9 if i == j:10 return11 if self.sz[i] < self.sz[j]:12 self.sz[j] += self.sz[i]13 self.id[i] = j14 else:15 self.sz[i] += self.sz[j]16 self.id[j] = i17 18 def getSize(self, i: int) -> int:19 return self.sz[i]20 21 def _find(self, u: int) -> int:22 if self.id[u] != u:23 self.id[u] = self._find(self.id[u])24 return self.id[u]25 26 27class Solution:28 def canTraverseAllPairs(self, nums: list[int]) -> bool:29 n = len(nums)30 mx = max(nums)31 maxPrimeFactor = self._sieveEratosthenes(mx + 1)32 primeToFirstIndex = collections.defaultdict(int)33 uf = UnionFind(n)34 35 for i, num in enumerate(nums):36 for prime_factor in self._getPrimeFactors(num, maxPrimeFactor):37 if prime_factor in primeToFirstIndex:38 uf.unionBySize(primeToFirstIndex[prime_factor], i)39 else:40 primeToFirstIndex[prime_factor] = i41 42 return any(uf.getSize(i) == n for i in range(n))43 44 def _sieveEratosthenes(self, n: int) -> list[int]:45 """Gets the minimum prime factor of i, where 1 < i <= n."""46 minPrimeFactors = [i for i in range(n + 1)]47 for i in range(2, int(n**0.5) + 1):48 if minPrimeFactors[i] == i: 49 for j in range(i * i, n, i):50 minPrimeFactors[j] = min(minPrimeFactors[j], i)51 return minPrimeFactors52 53 def _getPrimeFactors(self, num: int, minPrimeFactors: list[int]) -> list[int]:54 primeFactors = []55 while num > 1:56 divisor = minPrimeFactors[num]57 primeFactors.append(divisor)58 while num % divisor == 0:59 num = divisor60 return primeFactors61