Skip to main content

GCD Sort of an Array - Solution & Explanation

HardArrayMathUnion FindSorting18 min readAsked at: Amazon
Practice this problem

Problem Statement

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.

 

Example 1:

Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]

Example 2:

Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.

Example 3:

Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]

 

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 2 <= nums[i] <= 105

Approach Overview

Problem Overview: You are given an integer array and can swap two elements only if their gcd(a, b) > 1. Determine whether the array can be rearranged into sorted order using any number of such swaps.

Approach 1: Union-Find with Prime Decomposition (≈ O(n log M) time, O(M) space)

The key observation: if two numbers share a common prime factor (directly or through a chain of other numbers), they can eventually be swapped. Model this using Union Find. For each number, compute its prime factors using trial division or a smallest-prime-factor array. Union the number with each of its prime factors. This builds connected components where numbers sharing factors belong to the same group. After building the structure, create a sorted copy of the array. For each index i, check if nums[i] and sorted[i] belong to the same union-find root. If every position satisfies this condition, the array can be sorted. The insight is that swaps are possible anywhere inside a component because a chain of valid gcd swaps exists.

This approach combines number theory (prime factorization) with disjoint-set connectivity. Union operations connect numbers through shared factors, while path compression keeps operations nearly constant time. This is the most common interview solution because it directly models the swap constraints.

Approach 2: Connected Components with Sieve (≈ O(M log log M + n log M) time, O(M) space)

Instead of factoring each number individually, precompute smallest prime factors for all numbers up to the maximum value using a sieve. This converts factorization from repeated division into fast lookups. Iterate through the array and factor each value using the sieve table. As with the previous approach, union the value with each of its prime factors so that numbers sharing factors fall into the same component. After building components, compare the original array with the sorted array and verify that corresponding values belong to the same root.

The sieve reduces repeated factorization work when the maximum value is large. This method is essentially the same connectivity idea but optimized with precomputation. It is commonly paired with array processing and sorting checks to validate whether every element can move to its sorted position.

Recommended for interviews: Union-Find with prime factor decomposition is the expected approach. Start by explaining why swaps create connectivity groups based on shared prime factors. Brute-force pairwise gcd checks show understanding but scale poorly. Demonstrating union-find with factorization shows mastery of both graph connectivity and number theory optimization.

Approach 1: Approach 1: Union-Find with Prime Decomposition

This approach involves decomposing each number into its prime factors and then using the Union-Find data structure to connect numbers based on shared prime factors. The key insight is to treat numbers as nodes and shared prime factors as edges in a graph, allowing us to check if we can sort the array by ensuring any number can swap with its desired position in the sorted array via a common factor.

This C code implements the Union-Find data structure combined with prime factor decomposition. We initialize parent pointers for all numbers, then for each number, we find its parent, forming connected components in which swaps are permissible. The sorted array is checked against this condition.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N log(N)), where N is the number of elements in nums, due to sorting and union-find operations. Space Complexity: O(M), where M is the upper limit of the number range (10^5).

Try this approach in the editor →

Approach 2: Approach 2: Connected Components with Sieve

This approach leverages the Sieve of Eratosthenes to connect numbers sharing the same prime factors into connected components. Using these components, we assess if elements can shift positions based on common factor conditions for sorting.

In this C implementation, a version of the Sieve of Eratosthenes is used to determine prime factors and unite them in connected components using union-find. Sorting is validated by ensuring elements can belong to the same component

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N log(N)), where N is the number of elements in nums, due to sorting and connected component operations. Space Complexity: O(M), where M is the upper limit of the number range (10^5).

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Union-Find with Prime Decomposition

Time Complexity: O(N log(N)), where N is the number of elements in nums, due to sorting and union-find operations. Space Complexity: O(M), where M is the upper limit of the number range (10^5).

Approach 2: Connected Components with Sieve

Time Complexity: O(N log(N)), where N is the number of elements in nums, due to sorting and connected component operations. Space Complexity: O(M), where M is the upper limit of the number range (10^5).

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Union-Find with Prime DecompositionO(n log M)O(M)General case. Standard interview solution using union-find and factorization.
Connected Components with SieveO(M log log M + n log M)O(M)Better when many numbers share large ranges and repeated factorization would be expensive.

Video Solution

LeetCode 1998. GCD Sort of an Array • Happy Coding • 2,490 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is GCD Sort of an Array easy or hard?
GCD Sort of an Array is considered a Hard problem. It requires combining multiple concepts: gcd properties, prime factorization, union-find connectivity, and verifying element positions after sorting.
GCD Sort of an Array Python/Java solution
Python and Java implementations typically use a Union-Find class with path compression and union by rank. Each number is factored into primes, unioned with those primes, and then validated against a sorted copy of the array to ensure both elements share the same root.
How to solve GCD Sort of an Array in O(n)?
Pure O(n) is not practical because prime factorization or sieve preprocessing is required. The closest practical complexity is O(n log M) with union-find and prime factorization, or O(M log log M + n log M) using a sieve to accelerate factor lookups.
What is the best approach for GCD Sort of an Array?
Union-Find with prime factorization is the best approach. Each number is connected to its prime factors, creating components of values that can swap through gcd relationships. After building components, compare the original array with the sorted array and verify both elements belong to the same root. This runs in about O(n log M) time.
Is GCD Sort of an Array asked at Google/Amazon/Meta?
Problems combining union-find with number theory appear frequently in interviews at companies like Google, Amazon, and Meta. Variants involving connectivity through shared factors or grouping by gcd constraints are common in hard-level algorithm rounds.
What data structure is used in GCD Sort of an Array?
The core data structure is Union-Find (Disjoint Set Union). It groups numbers into connected components based on shared prime factors. A sieve or factorization helper from number theory is also used to extract prime factors efficiently.
What is the time complexity of GCD Sort of an Array?
The optimized union-find solution runs in roughly O(n log M) time where M is the maximum number in the array. Using a sieve adds a preprocessing step of O(M log log M). Union and find operations are nearly constant due to path compression.

Ready to solve this problem?

Practice GCD Sort of an Array with our built-in code editor and test cases.

Practice on FleetCode