Skip to content

Commit

Permalink
Time: 367 ms (60.00%) | Memory: 68.3 MB (60.00%) - LeetSync
Browse files Browse the repository at this point in the history
  • Loading branch information
ShatilKhan committed Feb 25, 2024
1 parent 9599e0c commit cfd09b6
Showing 1 changed file with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* @param {number[]} nums
* @return {boolean}
*/
var canTraverseAllPairs = function(nums) {
const numElements = nums.length;
if (numElements === 1) return true;

const disjointSet = Array.from({ length: numElements }, (_, index) => index);
const setSize = Array(numElements).fill(1);
const factorFirstOccurrence = new Map();

function findSetLeader(x) {
if (disjointSet[x] === x) return x;
disjointSet[x] = findSetLeader(disjointSet[x]);
return disjointSet[x];
}

function unionSets(x, y) {
const xLeader = findSetLeader(x);
const yLeader = findSetLeader(y);
if (xLeader === yLeader) return;
if (setSize[xLeader] < setSize[yLeader]) {
disjointSet[xLeader] = yLeader;
setSize[yLeader] += setSize[xLeader];
} else {
disjointSet[yLeader] = xLeader;
setSize[xLeader] += setSize[yLeader];
}
}

for (let i = 0; i < numElements; i++) {
let num = nums[i];
let divisor = 2;
while (divisor * divisor <= num) {
if (num % divisor === 0) {
if (factorFirstOccurrence.has(divisor)) {
unionSets(i, factorFirstOccurrence.get(divisor));
} else {
factorFirstOccurrence.set(divisor, i);
}
while (num % divisor === 0) {
num /= divisor;
}
}
divisor++;
}
if (num > 1) {
if (factorFirstOccurrence.has(num)) {
unionSets(i, factorFirstOccurrence.get(num));
} else {
factorFirstOccurrence.set(num, i);
}
}
}

return setSize[findSetLeader(0)] === numElements;
};

0 comments on commit cfd09b6

Please sign in to comment.