# GCD Sort Of An Array: Explained

GCD Sort Of An Array shows up often in coding rounds. Here is how I talk through it when the interviewer is watching.

## Key idea

Sieve prime factors and Union-Find every value with each of its primes (or with other values that share a factor). You may swap anything inside a component, so the array can be sorted iff nums[i] and sorted(nums)[i] lie in the same component for every i.

## Steps to say out loud

1. Restate the input and the exact ask, and nail down constraints and overflow.
2. Name the pattern (a heap or priority queue, Union-Find, interval scheduling, bitmask DP, a topological order, or a Trie) and why a nested scan or naive search fails.
3. Code it, then trace a short example plus one empty or already-solved edge case.

## Complexity

O(A log A + n α(A)).

## Common mistake

Only unioning adjacent equal-gcd pairs and missing a shared prime that links two non-neighbors.

## Practice tip

Time yourself: two minutes to explain, ten to code, three to test edges. Disclosure: I work on Linkjob AI. I also keep a practice cheat sheet at here.