Problem Description
Given an integer array nums, you can swap any two elements nums[i] and nums[j] if the greatest common divisor of nums[i] and nums[j] is greater than 1. Determine if it is possible to sort the array in non-decreasing order using these swaps.
Key Insights
- Two numbers can be swapped if they share a common prime factor (gcd > 1), which establishes a connection between them.
- The connections form groups (or connected components) where elements can be reordered arbitrarily.
- Union Find (Disjoint Set Union) is used to group indices that are connected based on common prime factors.
- After grouping, by sorting elements within each connected component, we can compare with the fully sorted array to verify if a global sort is possible.
- Prime factorization is key to determine the connectivity between numbers.
Space and Time Complexity
Time Complexity: O(n * log(max(nums)) + n α(n)) – Prime factorization has a logarithmic complexity per element and union-find operations are nearly constant (α(n)).
Space Complexity: O(n + max(nums)) – Extra space is used to maintain union-find arrays and mappings for factors.
Solution
The algorithm uses a union-find data structure to group indices of numbers that share a common prime factor. For each number, we perform prime factorization and union its index with indices of previously seen numbers sharing the same factor. Each group (or connected component) can be internally sorted. Finally, we create a sorted copy of the original array and check if by reordering numbers within each connected component, the overall sorted order is achieved. If yes, return true; otherwise, false.