GCD Sort of an Array - 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.

Input & Output

Example 1 — Numbers with Common Factors
$ Input: nums = [7,21,3]
Output: true
💡 Note: We can swap 21 and 3 since gcd(21,3) = 3 > 1, giving us [7,3,21]. This is sorted in non-decreasing order.
Example 2 — Numbers without Sufficient Connections
$ Input: nums = [5,2,6,2]
Output: false
💡 Note: gcd(5,2)=1, gcd(5,6)=1, gcd(2,6)=2>1, gcd(2,2)=2>1. The 5 cannot be moved from position 0, but it needs to be at position 2 in the sorted array [2,2,5,6].
Example 3 — Already Sorted
$ Input: nums = [10,5,9,3,15]
Output: false
💡 Note: gcd(10,5)=5>1, gcd(9,3)=3>1, gcd(9,15)=3>1, gcd(3,15)=3>1. However, the components are [10,5] and [9,3,15]. Number 5 needs to be at position 1 in sorted array [3,5,9,10,15], but it can only reach positions in component with 10.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • 2 ≤ nums[i] ≤ 105

Visualization

Tap to expand
GCD Sort: Can We Sort Using GCD-Based Swaps?7213Original Arraygcd(21,3) = 3 > 1 ✓Can swap!7321After Swap: [7, 3, 21] - Sorted! ✓Result: true
Understanding the Visualization
1
Input Analysis
Array [7,21,3] with GCD connections between pairs
2
Find Connections
gcd(21,3) = 3 > 1, so 21 and 3 can be swapped
3
Result
After swap: [7,3,21] which is sorted
Key Takeaway
🎯 Key Insight: Numbers can only be rearranged within their connected components formed by GCD > 1 relationships
Asked in
Google 12 Facebook 8
18.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen