Course Schedule II Solution | LeetCode-210: Medium | JavaScript Implementation

Manan Kumar Gupta
2 min readFeb 8, 2022

--

We will be seeing the solution to the LeetCode problem 210 in JavaScript. I hope you will find it useful.

Problem Statement:
There are a total of numCourses courses you have to take, labeled from 0 to numCourses — 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Link to Problem: https://leetcode.com/problems/course-schedule-ii/

Implementation:

var findOrder = function (numCourses, prerequisites) {
let countIncomingCounts = {};
let result = [];
let possibleQueue = [];
let graph = {};
for (let x = 0; x < prerequisites.length; x++) {
let i = prerequisites[x];
if (graph[i[1]]!=null) {
graph[i[1]].push(i[0]);
} else {
graph[i[1]] = [i[0]];
}
if (countIncomingCounts[i[0]]) {
countIncomingCounts[i[0]]++;
} else {
countIncomingCounts[i[0]] = 1;
}
}
for (let i = 0; i < numCourses; i++) {
if (!countIncomingCounts[i] || countIncomingCounts[i] == 0) {
possibleQueue.push(i);
}
}
while (possibleQueue.length != 0) {
let top = possibleQueue.shift(0);
result.push(top);
for (let i = 0; graph[top] && i < graph[top].length; i++) {
let adj = graph[top][i];
countIncomingCounts[adj] = countIncomingCounts[adj] - 1;
if (countIncomingCounts[adj] == 0) {
possibleQueue.push(adj);
}
}
}
return result.length!=numCourses?[]:result;
};

Thank you for reading hope this code is helpful to you.

--

--

Manan Kumar Gupta
Manan Kumar Gupta

Written by Manan Kumar Gupta

I am Frontend Developer, exploring the power of Javascript. I have worked on Angular, ReactJS and React Native.

No responses yet