GCD Sort of an Array Problem
Description
LeetCode Problem 1998.
You are given an integer array nums, and you can perform the following operation any number of times on nums:
- Swap the positions of two elements
nums[i]andnums[j]ifgcd(nums[i], nums[j]) > 1wheregcd(nums[i], nums[j])is the greatest common divisor ofnums[i]andnums[j].
Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Example 1:
Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]
Example 2:
Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.
Example 3:
Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]
Constraints:
1 <= nums.length <= 3 * 10^42 <= nums[i] <= 10^5
Solution
Approach: Union-Find on Prime Factors
Two elements can be swapped when they share a prime factor, and swaps can be chained, so the elements form connected groups. Inside a group any order can be reached; across groups elements never move.
Build the groups with union-find: for every number in nums, union it with each of its prime factors. Two numbers end up in the same set exactly when a chain of shared prime factors links them. To list the prime factors, run a sieve up to max(nums) and record each prime p in the list of every multiple of p.
Now sort a copy of the array. The array can be sorted if and only if every position i holds a value in the same group as the value that belongs there: whenever sorted[i] != nums[i], the two must have the same root.
Complexity: O(M log log M + n log n) time and O(M) space, where M is the largest value in nums and n its length.
from collections import defaultdict
class Solution:
def gcdSort(self, nums: List[int]) -> bool:
n = 10**5 + 10
p = list(range(n))
f = defaultdict(list)
mx = max(nums)
for i in range(2, mx + 1):
if f[i]:
continue
for j in range(i, mx + 1, i):
f[j].append(i)
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
for i in nums:
for j in f[i]:
p[find(i)] = find(j)
s = sorted(nums)
for i, num in enumerate(nums):
if s[i] != num and find(num) != find(s[i]):
return False
return True