Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

GCD Sort of an Array

XPChallenge Points: 30
levelLevel: Hard

You are given an integer array nums. You are allowed to perform this special operation any number of times:

  • Pick two indices i and j and swap nums[i] with nums[j] only if
    gcd(nums[i], nums[j]) > 1
    (i.e., the two numbers share a common factor greater than 1).

Your task is to determine whether it is possible to rearrange the array into non-decreasing order by using only these gcd-based swaps.

If sorting is achievable → return true, otherwise → return false.

Example 1:

Input: nums = [12, 6, 9]

Output: true

Explanation:

gcd(12, 6) = 6 → can swap gcd(6, 9) = 3 → can swap So full sorting is possible.

Example 2:

Input: nums = [11, 7, 13]

Output: false

Explanation:

All numbers are prime and share no common factor > 1. No swaps are allowed → cannot sort.

Example 3:

Input: nums = [4, 3, 6, 9]

Output: true

Explanation:

gcd(4, 6) = 2 gcd(6, 9) = 3 With these valid swaps, sorted order is possible.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result