- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 60 lines of Python from the credited upstream file 1998.py.
- The implementation visibly relies on sequence storage.
- 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.rank = [0] * n5 6 def unionByRank(self, u: int, v: int) -> None:7 i = self.find(u)8 j = self.find(v)9 if i == j:10 return False11 if self.rank[i] < self.rank[j]:12 self.id[i] = j13 elif self.rank[i] > self.rank[j]:14 self.id[j] = i15 else:16 self.id[i] = j17 self.rank[j] += 118 return True19 20 def find(self, u: int) -> int:21 if self.id[u] != u:22 self.id[u] = self.find(self.id[u])23 return self.id[u]24 25 26class Solution:27 def gcdSort(self, nums: list[int]) -> bool:28 mx = max(nums)29 minPrimeFactors = self._sieveEratosthenes(mx + 1)30 uf = UnionFind(mx + 1)31 32 for num in nums:33 for primeFactor in self._getPrimeFactors(num, minPrimeFactors):34 uf.unionByRank(num, primeFactor)35 36 for a, b in zip(nums, sorted(nums)):37 38 if uf.find(a) != uf.find(b):39 return False40 41 return True42 43 def _sieveEratosthenes(self, n: int) -> list[int]:44 """Gets the minimum prime factor of i, where 1 < i <= n."""45 minPrimeFactors = [i for i in range(n + 1)]46 for i in range(2, int(n**0.5) + 1):47 if minPrimeFactors[i] == i: 48 for j in range(i * i, n, i):49 minPrimeFactors[j] = min(minPrimeFactors[j], i)50 return minPrimeFactors51 52 def _getPrimeFactors(self, num: int, minPrimeFactors: list[int]) -> list[int]:53 primeFactors = []54 while num > 1:55 divisor = minPrimeFactors[num]56 primeFactors.append(divisor)57 while num % divisor == 0:58 num = divisor59 return primeFactors60