File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ class Solution {
5
+ validTree ( n , edges ) {
6
+ // initialize Union-Find data structure
7
+ const parent = Array ( n )
8
+ . fill ( 0 )
9
+ . map ( ( _ , index ) => index ) ;
10
+ const rank = Array ( n ) . fill ( 1 ) ;
11
+
12
+ // find function with path compression
13
+ function find ( x ) {
14
+ if ( parent [ x ] !== x ) {
15
+ parent [ x ] = find ( parent [ x ] ) ;
16
+ }
17
+ return parent [ x ] ;
18
+ }
19
+
20
+ // union function with union by rank
21
+ function union ( x , y ) {
22
+ const rootX = find ( x ) ;
23
+ const rootY = find ( y ) ;
24
+ if ( rootX !== rootY ) {
25
+ if ( rank [ rootX ] > rank [ rootY ] ) {
26
+ parent [ rootY ] = rootX ;
27
+ } else if ( rank [ rootX ] < rank [ rootY ] ) {
28
+ parent [ rootX ] = rootY ;
29
+ } else {
30
+ parent [ rootY ] = rootX ;
31
+ rank [ rootX ] += 1 ;
32
+ }
33
+ } else {
34
+ // if rootX == rootY, there is a cycle
35
+ return false ;
36
+ }
37
+ return true ;
38
+ }
39
+
40
+ // process each edge
41
+ for ( const [ u , v ] of edges ) {
42
+ if ( ! union ( u , v ) ) {
43
+ // if union returns false, a cycle is detected
44
+ return false ;
45
+ }
46
+ }
47
+
48
+ // if all unions are successful, it's a valid tree
49
+ return true ;
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments