Skip to content

Commit ad131ab

Browse files
committed
Added courseSchedule solution
1 parent 6838953 commit ad131ab

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

course-schedule/nhistory.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number} numCourses
3+
* @param {number[][]} prerequisites
4+
* @return {boolean}
5+
*/
6+
var canFinish = function (numCourses, prerequisites) {
7+
// Initialize in-degree array and graph map
8+
const inDegree = Array(numCourses).fill(0);
9+
const graph = new Map();
10+
11+
// Build the graph and compute in-degrees
12+
prerequisites.forEach(([course, pre]) => {
13+
inDegree[course]++;
14+
if (!graph.has(pre)) {
15+
graph.set(pre, []);
16+
}
17+
graph.get(pre).push(course);
18+
});
19+
20+
// Queue for courses with no prerequisites
21+
const queue = [];
22+
for (let i = 0; i < numCourses; i++) {
23+
if (inDegree[i] === 0) {
24+
queue.push(i);
25+
}
26+
}
27+
28+
// Process the courses
29+
let count = 0;
30+
while (queue.length > 0) {
31+
const course = queue.shift();
32+
count++;
33+
if (graph.has(course)) {
34+
graph.get(course).forEach((nextCourse) => {
35+
inDegree[nextCourse]--;
36+
if (inDegree[nextCourse] === 0) {
37+
queue.push(nextCourse);
38+
}
39+
});
40+
}
41+
}
42+
43+
// Return true if all courses can be finished
44+
return count === numCourses;
45+
};
46+
47+
// TC: O(V + E)
48+
// V is the number of courses, E is the number of prerequisites.
49+
// SC: O(V + E)

0 commit comments

Comments
 (0)