You are given an integer array nums, and you can perform the following operation any number of times on nums:
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 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 * 1042 <= nums[i] <= 105When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to GCD sorting is all about trying every possible arrangement of the numbers. We'll check if each arrangement meets the GCD criteria after we sort it.
Here's how the algorithm would work step-by-step:
def gcd_sort_brute_force(numbers): import itertools
def greatest_common_divisor(first_number, second_number):
while(second_number):
first_number, second_number = second_number, first_number % second_number
return first_number
def check_gcd_criteria(original_numbers, sorted_numbers):
for index in range(len(sorted_numbers) - 1):
if greatest_common_divisor(sorted_numbers[index], sorted_numbers[index + 1]) != greatest_common_divisor(original_numbers[index], original_numbers[index + 1]):
return False
return True
# Generate all possible permutations of the input array
for permutation in itertools.permutations(numbers):
permutation_list = list(permutation)
sorted_permutation = sorted(permutation_list)
# Check if the current permutation meets the GCD criteria
if len(numbers) > 1:
if check_gcd_criteria(numbers, sorted_permutation):
return True
else:
return True
# If no permutation satisfies the condition, return False
return FalseWe want to check if we can sort the numbers by only swapping numbers that share a common factor (greater than 1). Instead of directly sorting, we'll build a connection map showing which numbers *could* be swapped and then check if we could indirectly sort the array.
Here's how the algorithm would work step-by-step:
def gcd_sort(numbers):
array_length = len(numbers)
max_number = max(numbers)
parent = list(range(max_number + 1))
def find(number):
if parent[number] != number:
parent[number] = find(parent[number])
return parent[number]
def union(number_x, number_y):
root_x = find(number_x)
root_y = find(number_y)
if root_x != root_y:
parent[root_x] = root_y
# Iterate from 2 to the max to find factors.
for factor in range(2, max_number + 1):
for number in range(factor, max_number + 1, factor):
# Connect all numbers divisible by the same factor.
union(factor, number)
sorted_numbers = sorted(numbers)
# Checking connectivity between unsorted and sorted positions.
for index in range(array_length):
if find(numbers[index]) != find(sorted_numbers[index]):
return False
return True| Case | How to Handle |
|---|---|
| Empty or null input array | Return true, as an empty array is trivially considered sorted in this context because no swap needs to be made. |
| Array with only one element | Return true, as a single-element array is also trivially considered sorted because there's nothing to sort. |
| Array with all identical values | The algorithm should correctly identify this as already sorted (or sortable without actual swaps), returning true. |
| Large input array (maximum-sized) | Ensure the used sorting and GCD algorithms scale efficiently to avoid time limit exceeded errors; consider using an optimized sorting algorithm and a fast GCD implementation (e.g., binary GCD). |
| Integer overflow during GCD calculation | Use a data type large enough to prevent overflow (e.g., long in Java/C++) when calculating GCDs, or bitwise operations to avoid multiplication. |
| Input array contains zero | The GCD function must handle zero inputs gracefully, typically returning the non-zero number or zero if both inputs are zero. |
| Input array contains large prime numbers | GCD calculation involving large primes may be computationally expensive, but the algorithm should still function correctly, although possibly slower. |
| No valid solution exists (array is not GCD sortable) | The algorithm must correctly identify when the array cannot be sorted by GCD swaps and return false, which will be indicated when there is an element out of order and no element earlier in the array has a gcd with it. |