Number of Operations to Make Network Connected LeetCode solution in JavaScript

1
/**
2
* @param {number} n
3
* @param {number[][]} connections
4
* @return {number}
5
*/
6
class UnionFind {
7
constructor(n) {
8
this.root = new Array(n).fill().map((_, index) => index);
9
this.components = n;
10
}
11
find(x) {
12
if (x == this.root[x]) return x;
13
return (this.root[x] = this.find(this.root[x]));
14
}
15
union(x, y) {
16
const rootX = this.find(x);
17
const rootY = this.find(y);
18
if (rootX != rootY) {
19
this.root[rootY] = rootX;
20
this.components--;
21
}
22
}
23
}
24
var makeConnected = function (n, connections) {
25
// We need at least n - 1 cables to connect all nodes (like a tree).
26
if (connections.length < n - 1) return -1;
27
const uf = new UnionFind(n);
28
for (const [a, b] of connections) {
29
uf.union(a, b);
30
}
31
return uf.components - 1;
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0