<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 DisJointSets():
    def __init__(self,N):
        # Initially, all elements are single element subsets
        self._parents = [node for node in range(N)]
        self._ranks = [1 for _ in range(N)]

    def find(self, u):
        while u != self._parents[u]:
            # path compression technique
            self._parents[u] = self._parents[self._parents[u]]
            u = self._parents[u]
        return u

    def connected(self, u, v):
        return self.find(u) == self.find(v)

    def union(self, u, v):
        # Union by rank optimization
        root_u, root_v = self.find(u), self.find(v)
        if root_u == root_v:
            return True

        # I modified this to have proper rank sizes
        if self._ranks[root_u] > self._ranks[root_v]:
            self._parents[root_v] = root_u
            self._ranks[root_u] += self._ranks[root_v]
        elif self._ranks[root_v] > self._ranks[root_u]:
            self._parents[root_u] = root_v
            self._ranks[root_v] += self._ranks[root_u]
        else:
            self._parents[root_u] = root_v
            self._ranks[root_v] += self._ranks[root_u]
        return False
    join = union

    def n_components(self):
        return sum(parent == i for i, parent in enumerate(self._parents))

    def copy(self):
        new = DisJointSets(len(self._parents))
        new._parents = self._parents[:]
        new._ranks = self._ranks[:]
        return new

    def components(self):
        componentsByRoot = defaultdict(list)
        for i in range(len(self._parents)):
            componentsByRoot[self.find(i)].append(i)
        return componentsByRoot.values()




class Solution:
    def gcdSort(self, nums: List[int]) -> bool:
        # Split up into groups by gcd
        # sort those
        # is it sorted?

        n = len(nums)
        # we define a group as the connected component of indexes, where indexes are connected if they share a factor.
        indicesWithFactor = defaultdict(list)
        for i, num in enumerate(nums):
            for factor in prime_factors(num):
                if factor > 1:
                    indicesWithFactor[factor].append(i)
        dsu = DisJointSets(n)
        for sharedIndices in indicesWithFactor.values():
            for i in sharedIndices:
                dsu.join(i, sharedIndices[0])
        for component in dsu.components():
            componentValues = [nums[i] for i in component]
            componentValues.sort()
            for i, val in zip(component, componentValues):
                nums[i] = val
        return sorted(nums) == nums

            


def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors
1751