File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments