#1998

GCD Sort of an Array

Hard
ArrayMathUnion-FindSortingNumber TheoryUnion-FindSortingGraph Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses the Union-Find (Disjoint Set Union) data structure to group elements that can be swapped based on their GCD. This allows us to efficiently determine if we can sort the array by checking if all elements in the same group can be rearranged.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a Union-Find structure to group indices based on GCD connections.
  2. 2Step 2: For each pair of elements, if gcd(nums[i], nums[j]) > 1, union their indices.
  3. 3Step 3: For each group of connected indices, check if the elements can be sorted within that group.
solution.py31 lines
1class UnionFind:
2    def __init__(self, n):
3        self.parent = list(range(n))
4    def find(self, x):
5        if self.parent[x] != x:
6            self.parent[x] = self.find(self.parent[x])
7        return self.parent[x]
8    def union(self, x, y):
9        rootX = self.find(x)
10        rootY = self.find(y)
11        if rootX != rootY:
12            self.parent[rootY] = rootX
13
14
15def canSort(nums):
16    n = len(nums)
17    uf = UnionFind(n)
18    for i in range(n):
19        for j in range(i + 1, n):
20            if math.gcd(nums[i], nums[j]) > 1:
21                uf.union(i, j)
22    groups = {}
23    for i in range(n):
24        root = uf.find(i)
25        if root not in groups:
26            groups[root] = []
27        groups[root].append(nums[i])
28    for group in groups.values():
29        if sorted(group) != sorted(group):
30            return False
31    return True

Complexity note: The complexity is dominated by the union-find operations and sorting the groups, leading to a more efficient solution than the brute force approach.

  • 1Elements that share a GCD greater than 1 can be swapped, forming connected components.
  • 2Sorting within each connected component must yield the same result as sorting the entire array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.