GCD Sort of an Array — LeetCode 1998 Python Solution
- Problem
- #1998
- Pattern
- Union-Find
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Example
- Input
- nums = [7,21,3]
- Output
- true
- Explanation
- We can sort [7,21,3] by performing the following operations:
Python solution
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 TrueComplexity
| Measure | Complexity |
|---|---|
| Time | Near O(n) (amortized) |
| Space | O(n) auxiliary |
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1998. GCD Sort of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Union Find.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1998. GCD Sort of an Array?
- LeetCode 1998. GCD Sort of an Array is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1998. GCD Sort of an Array?
- The Python solution on this page runs in Near O(n) (amortized).
- What is the space complexity of LeetCode 1998. GCD Sort of an Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1998. GCD Sort of an Array cover?
- LeetCode 1998. GCD Sort of an Array is tagged Union Find, Array, Math, Number Theory and Sorting on LeetCode.