Skip to content

Commit a05471f

Browse files
committed
Add week 9 solutions: courseSchedule
1 parent 6200cb5 commit a05471f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

course-schedule/yolophg.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time Complexity: O(m * n)
2+
// Space Complexity: O(m * n)
3+
4+
// initialize an array to keep track of the in-degrees for each course
5+
let inDegree = new Array(numCourses).fill(0);
6+
// initialize an adjacency list to represent the graph of courses
7+
let adjList = new Array(numCourses).fill(0).map(() => []);
8+
9+
// fill the in-degree array and adjacency list based on the prerequisites
10+
for (let [course, prereq] of prerequisites) {
11+
// increment the in-degree of the course
12+
inDegree[course]++;
13+
// add the course to the adjacency list of the prerequisite
14+
adjList[prereq].push(course);
15+
}
16+
17+
// initialize a queue to keep track of courses with no prerequisites (in-degree of 0)
18+
let queue = [];
19+
for (let i = 0; i < numCourses; i++) {
20+
if (inDegree[i] === 0) {
21+
queue.push(i);
22+
}
23+
}
24+
25+
// initialize a counter to keep track of the number of courses that have been processed
26+
let count = 0;
27+
28+
// process the courses with no prerequisites
29+
while (queue.length > 0) {
30+
// get a course from the queue
31+
let current = queue.shift();
32+
// increment the counter as this course can be taken
33+
count++;
34+
35+
// iterate through the adjacency list of the current course
36+
for (let neighbor of adjList[current]) {
37+
// decrement the in-degree of the neighboring course
38+
inDegree[neighbor]--;
39+
// if in-degree becomes 0, add it to the queue
40+
if (inDegree[neighbor] === 0) {
41+
queue.push(neighbor);
42+
}
43+
}
44+
}
45+
46+
// if the count of processed courses equals the total number of courses, return true
47+
return count === numCourses;

0 commit comments

Comments
 (0)