<p>You are given an integer array <code>nums</code>, and you can perform the following operation <strong>any</strong> number of times on <code>nums</code>:</p>

<ul>
	<li>Swap the positions of two elements <code>nums[i]</code> and <code>nums[j]</code> if <code>gcd(nums[i], nums[j]) &gt; 1</code> where <code>gcd(nums[i], nums[j])</code> is the <strong>greatest common divisor</strong> of <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>

<p>Return <code>true</code> <em>if it is possible to sort </em><code>nums</code><em> in <strong>non-decreasing</strong> order using the above swap method, or </em><code>false</code><em> otherwise.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [7,21,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [<u><strong>21</strong></u>,<u><strong>7</strong></u>,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [<u><strong>3</strong></u>,7,<u><strong>21</strong></u>]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,2,6,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to sort the array because 5 cannot be swapped with any other element.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [10,5,9,3,15]
<strong>Output:</strong> true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [<u><strong>15</strong></u>,5,9,3,<u><strong>10</strong></u>]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [<u><strong>3</strong></u>,5,9,<u><strong>15</strong></u>,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,<u><strong>10</strong></u>,<u><strong>15</strong></u>]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>2 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

class UnionFind:
    def __init__(self, arr):
        self.parent = list(range(len(arr)))
        self.rank = [1] * len(arr)
        self.arr = arr
        self.value_to_index = {value: i for i, value in enumerate(arr)}
        self.factor_to_index = defaultdict(list)
        
        # Populate the union-find structure based on prime factors
        for i, num in enumerate(arr):
            factors = self.get_prime_factors(num)
            for factor in factors:
                self.factor_to_index[factor].append(i)
        
        # Union all indices that share the same prime factor
        for indices in self.factor_to_index.values():
            for i in range(1, len(indices)):
                self.union(indices[0], indices[i])
    
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # Path compression
        return self.parent[x]
    
    def union(self, x, y):
        rootX = self.find(x)
        rootY = self.find(y)
        
        if rootX != rootY:
            # Union by rank
            if self.rank[rootX] > self.rank[rootY]:
                self.parent[rootY] = rootX
            elif self.rank[rootX] < self.rank[rootY]:
                self.parent[rootX] = rootY
            else:
                self.parent[rootY] = rootX
                self.rank[rootX] += 1

    def get_prime_factors(self, x):
        i = 2
        factors = set()
        while i * i <= x:
            if x % i == 0:
                factors.add(i)
                while x % i == 0:
                    x //= i
            i += 1
        if x > 1:
            factors.add(x)
        return factors
    
    def connected(self, value1, value2):
        # Find indices corresponding to the given values
        if value1 not in self.value_to_index or value2 not in self.value_to_index:
            return False
        
        i = self.value_to_index[value1]
        j = self.value_to_index[value2]
        
        # Check if the indices are connected
        return self.find(i) == self.find(j)

class Solution:
    def gcdSort(self, nums: List[int]) -> bool:
        info = sorted(nums)
        indices = defaultdict(list)
        uf = UnionFind(info)

        for idx, num in enumerate(info):
            indices[num].append(idx)

        def factorize(num): 
            factors = defaultdict(int)
            factor = 2

            while factor**2 <= num:
                while not num % factor:
                    factors[factor] += 1
                    num //= factor

                factor += 1

            if num > 1:
                factors[num] += 1

            return factors


        for idx, num in enumerate(nums):
            if nums[idx] == info[idx]:
                continue

            while nums[idx] != info[idx]:
                target = indices[nums[idx]].pop()
                if not uf.connected(nums[idx], nums[target]):
                    return False

                temp = nums[idx]
                nums[idx] = nums[target]
                nums[target] = temp

        return True
1861