The GCD Sort of an Array coding problem asks if you can sort an array in non-decreasing order using a specific swap operation. You are allowed to swap any two elements nums[i] and nums[j] if their Greatest Common Divisor (GCD) is strictly greater than 1. You can perform this swap any number of times.
Amazon asks this Hard difficulty Math and Graph problem to test your knowledge of Union Find (Disjoint Set) and prime factorization. It evaluates your ability to recognize that if elements can be swapped, they belong to the same "connected component." The problem boils down to checking if the original element and the element that should be in its place after sorting belong to the same component.
This problem uses Union Find and Sieve of Eratosthenes.
original[i] != sorted[i], they must be in the same DSU component to be swappable. If they aren't, return False.nums = [7, 21, 3]
[3, 7, 21].Whenever a problem says "you can swap A and B if they share a property, can you reach state X?", it is almost always a Union Find problem. The swappable items form a connected component, and you just need to verify that items only need to move within their own component.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Graph Connectivity With Threshold | Hard | Solve | |
| Greatest Common Divisor Traversal | Hard | Solve | |
| Largest Component Size by Common Factor | Hard | Solve | |
| Minimum Deletions to Make Array Divisible | Hard | Solve | |
| Make K-Subarray Sums Equal | Medium | Solve |