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 of an Array INPUT nums = [7, 21, 3] 7 i=0 21 i=1 3 i=2 GCD Relationships: gcd(7, 21) = 7 > 1 gcd(21, 3) = 3 > 1 gcd(7, 3) = 1 (no swap) 7 -- 21 -- 3 (connected) 7 21 3 ALGORITHM STEPS 1 Build Union-Find Group nums by shared prime factors 2 Factorize Numbers 7=7, 21=3*7, 3=3 Union by factors 3 Union Groups 7--21 via factor 7 21--3 via factor 3 4 Check Sortability Compare with sorted Same group = OK Union-Find Groups: {7, 21, 3} - ALL CONNECTED Can swap any pair transitively FINAL RESULT Sorting Process: Original: 7 21 3 Swap 7,21: 21 7 3 Swap 21,3: 3 7 21 SORTED! 3 7 21 Output: true Key Insight: Use Union-Find with prime factorization. Numbers sharing a common factor > 1 are connected. If all elements that need to swap positions are in the same connected component, sorting is possible. Transitive swaps allow indirect connections: 7--21--3 means 7 and 3 can be reordered via 21. TutorialsPoint - GCD Sort of an Array | Optimal Solution (Union-Find + Prime Factorization)
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