Skip to content

Commit 10d7f88

Browse files
committed
Add week 10 solutions: graphValidTree
1 parent 7172ab9 commit 10d7f88

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

graph-valid-tree/yolophg.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
 (0)