Ctrl K

Sorting With Shared-Divisor Swaps

Hard
You are given an integer array values. You may swap two elements any number of times, but only when they have a common divisor greater than 1 (their GCD is above 1). Return True if such swaps can put the array in non-decreasing order, and False otherwise.
Example 1
values=[15, 4, 10, 6] → True

15 and 10 share 5, 4 and 10 share 2, 6 and 15 share 3: everything is linked, so any order is reachable, including [4, 6, 10, 15].

Example 2
values=[9, 7, 3] → True

7 shares no divisor above 1 with 9 or 3, so it stays put. Luckily it already sits where the sorted array wants it, and 9 and 3 can swap: [3, 7, 9].

Example 3
values=[11, 2, 4] → False

11 cannot move at all, yet in sorted order it has to end up last.

Constraints
  • 1 ≤ len(values) ≤ 3·10⁴
  • 2 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Shared-Factor Group HardTowns Joined by Big Divisors HardSmallest Divides Them All HardAll Linked by Common Factors HardGroups With a Small LCM Hard
loading Python…
Input
values=[15, 4, 10, 6]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 167 tests on the server, hidden ones included.