Skip to content

Commit e6b8cf7

Browse files
Jeehay28Jeehay28
authored andcommitted
Add course-schedule solution in TS
1 parent 350e8c0 commit e6b8cf7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

course-schedule/Jeehay28.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// TC: O(V + E), V = numCourses, E = prerequisites.length
2+
// SC: O(V + E)
3+
4+
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
5+
// 0: [1]
6+
// 1: []
7+
8+
const graph = new Map<number, number[]>();
9+
10+
// Initialize all courses
11+
for (let i = 0; i < numCourses; i++) {
12+
graph.set(i, []);
13+
}
14+
15+
// Build the graph
16+
for (const [crs, pre] of prerequisites) {
17+
graph.get(crs)!.push(pre);
18+
}
19+
20+
const traversing = new Set<number>();
21+
const finished = new Set<number>();
22+
23+
const canFinish = (crs: number): boolean => {
24+
if (traversing.has(crs)) return false; // cycle detected
25+
26+
if (finished.has(crs)) return true; // already visited
27+
28+
traversing.add(crs);
29+
30+
for (const pre of graph.get(crs)!) {
31+
if (!canFinish(pre)) return false;
32+
}
33+
34+
traversing.delete(crs);
35+
finished.add(crs);
36+
37+
return true;
38+
};
39+
40+
for (const crs of graph.keys()) {
41+
if (!canFinish(crs)) return false;
42+
}
43+
44+
return true;
45+
}

0 commit comments

Comments
 (0)