GCD Sort of an Array LeetCode solution in JavaScript

1
var gcdSort = function (nums) {
2
// group numbers by their prime factors
3
const unionFind = {};
4
const find = (x) =>
5
(unionFind[x] = unionFind[x] === x ? x : find(unionFind[x]));
6
const union = (x, y) => (unionFind[find(y)] = unionFind[find(x)]);
7
for (const num of nums) {
8
if (!unionFind[num]) {
9
unionFind[num] = num;
10
}
11
const primeFactors = getPrimeFactors(num);
12
for (const primeFactor of primeFactors) {
13
if (!unionFind[primeFactor]) {
14
unionFind[primeFactor] = primeFactor;
15
}
16
union(primeFactor, num);
17
}
18
}
19

20
// see if it's possible to swap nums to equal sorted by checking the groups
21
const sortedNums = [...nums].sort((a, b) => a - b);
22
return nums.every((num, i) => find(num) === find(sortedNums[i]));
23
};
24

25
function getPrimeFactors(n) {
26
const primeFactors = new Set();
27
while (n % 2 === 0) {
28
primeFactors.add(2);
29
n /= 2;
30
}
31

32
for (let i = 3; i * i <= n; i += 2) {
33
while (n % i === 0) {
34
primeFactors.add(i);
35
n /= i;
36
}
37
}
38
if (n > 1) {
39
primeFactors.add(n);
40
}
41
return primeFactors;
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0