Skip to content

Commit a2c22bf

Browse files
committed
Add week 10 solutions: numberOfConnectedComponentsInAnUndirectedGraph
1 parent 10d7f88 commit a2c22bf

File tree

1 file changed

+39
-0
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time Complexity: O(n + m) m : number of edges
2+
// Space Complexity: O(n)
3+
4+
class Solution {
5+
countComponents(n, edges) {
6+
// initialize the parent array where each node is its own parent initially
7+
const parent = new Array(n).fill(0).map((_, index) => index);
8+
9+
// to find the root of a node with path compression
10+
const find = (node) => {
11+
if (parent[node] !== node) {
12+
parent[node] = find(parent[node]);
13+
}
14+
return parent[node];
15+
};
16+
17+
// to union two nodes
18+
const union = (node1, node2) => {
19+
const root1 = find(node1);
20+
const root2 = find(node2);
21+
if (root1 !== root2) {
22+
parent[root1] = root2;
23+
}
24+
};
25+
26+
// union all the edges
27+
for (let [a, b] of edges) {
28+
union(a, b);
29+
}
30+
31+
// count the number of unique roots
32+
const uniqueRoots = new Set();
33+
for (let i = 0; i < n; i++) {
34+
uniqueRoots.add(find(i));
35+
}
36+
37+
return uniqueRoots.size;
38+
}
39+
}

0 commit comments

Comments
 (0)