GCD Sort of an Array
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]) > 1, wheregcd(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
trueWe can sort
[7, 21, 3] by swapping 7 with 21, then swapping 21 with 3, since each swap has gcd greater than 1.Example 2
Input
nums = [5,2,6,2]Output
falseIt is impossible to sort the array because
5 cannot be swapped with any other element.Constraints
- 1 <= nums.length <= 3 * 10^4
- 2 <= nums[i] <= 10^5