Imagine you have an array of numbers, but you can only swap two numbers if they share a common factor greater than 1 (their GCD > 1). Your goal is to determine whether you can sort this array in non-decreasing order using only these restricted swaps.
The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that divides both numbers. For example:
gcd(6, 9) = 3→ Can swap because 3 > 1gcd(4, 10) = 2→ Can swap because 2 > 1gcd(7, 11) = 1→ Cannot swap because 1 is not > 1
This problem tests your understanding of connected components and number theory. Elements that can be transitively swapped through a chain of GCD relationships form a connected group, and within each group, elements can be arranged in any order.
Input & Output
Visualization
Time & Space Complexity
For each of O(n²) iterations, we check O(n²) pairs and compute GCD in O(log(max(nums))) time
Space for the working copy of the array
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- 2 ≤ nums[i] ≤ 105
- All elements are at least 2 (no 1's that would make GCD always 1)