You are viewing a single comment's thread. Return to all comments →
function journeyToMoon(n: number, astronaut: number[][]): number { const parentArr = Array.from({length: n},(_, i) => i); const size = Array(n).fill(1); const findParent = (el: number): number => { while (parentArr[el] !== el) { el = parentArr[el]; } return el; } const unite = (el1: number, el2:number) => { el1 = findParent(el1); el2 = findParent(el2); if (el1 !== el2) { if (size[el1] > size[el2]) { size[el1] += size[el2]; parentArr[el2] = el1; size[el2] = 0; } else { size[el2] += size[el1]; parentArr[el1] = el2; size[el1] = 0; } } } for (const query of astronaut) { unite(query[0], query[1]) } let res = 0; for (let i = 0; i < n; i++) { if (size[i] !== 0) { res += size[i]*(n-size[i]); } } return res/2; }
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
TypeScript (Using UnionFind)