Tree of Coprimes LeetCode solution in JavaScript
1var getCoprimes = function (nums, edges) {2const node = {};3const ans = Array(nums.length).fill(null);45function addNode(f, t) {6if (!node[f]) {7node[f] = [];8}9node[f].push(t);10}1112edges.forEach(([f, t]) => {13addNode(f, t);14addNode(t, f);15});1617function gcd(a, b) {18while (b) [a, b] = [b, a % b];19return a;20}2122const map = [];23for (let i = 0; i < 51; i++) {24map[i] = [];25for (let j = 0; j < 51; j++) {26map[i][j] = gcd(i, j);27}28}2930let pi = -1;31let path = Array(nums.length);32function check(v) {33if (ans[v] !== null) return;34ans[v] = -1;35let a = nums[v];36for (let k = pi; k >= 0; k--) {37let b = nums[path[k]];38if (map[a][b] === 1) {39ans[v] = path[k];40break;41}42}43if (node[v]) {44path[++pi] = v;45node[v].forEach((child) => check(child));46pi--;47}48}4950for (let i = 0; i < nums.length; i++) {51check(i);52}5354return ans;55};