Problem overview
The method canFinish(numCourses, prerequisites) gets the number of courses, labeled 0 to numCourses - 1, and an array of pairs. A pair [a, b] means course b must be taken before course a. The method returns true if every course can be taken in some order that respects all the pairs, and false otherwise.
With numCourses = 2 and prerequisites = [[1, 0]], take course 0 and then course 1, so the answer is true. With [[1, 0], [0, 1]], each course waits for the other, so neither can ever start and the answer is false.
Approach: take courses whose prerequisites are done
Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that needs it. An order of all the courses in which every arrow points forward is a topological order. All courses can be finished exactly when such an order exists, which happens exactly when the arrows contain no cycle.
Kahn's algorithm builds the order greedily:
- Count, for every course, how many prerequisites it still waits for. This is its in-degree, the number of arrows pointing into it.
- Put every course with a count of 0 into a queue. Those can be taken now.
- Take the courses from the queue one at a time. Taking a course removes its outgoing arrows: each course that waited for it has one prerequisite fewer. When a count reaches 0, that course joins the queue.
- If all courses were taken, the answer is
true. Courses on a cycle never reach a count of 0, and neither does any course that needs one of them, so the number taken falls short.
The example numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] produces these structures. The first line is the graph (position b lists the courses waiting for b) and the second is the starting in-degree:
graph: [[1,2],[3],[3],[]]
inDegree: [0,1,1,2]
Only course 0 starts in the queue. Taking each course in turn gives:
took 0: inDegree [0,0,0,2] queue [0,1,2]
took 1: inDegree [0,0,0,1] queue [0,1,2]
took 2: inDegree [0,0,0,0] queue [0,1,2,3]
took 3: inDegree [0,0,0,0] queue [0,1,2,3]
Course 3 joins the queue only after both of its prerequisites, 1 and 2, are taken. All four courses were taken, so the answer is true.
Step by step
- Build
graphwithArray.from({length: numCourses}, () => []). The callback runs once per course, so every course gets its own empty array.graph[b]will list the courses that wait forb. - Build
inDegree, an array of zeros.inDegree[a]counts the prerequisites of courseathat are not taken yet. - Loop over
prerequisiteswithfor...of. Each pair becomes one arrow. - Record the arrow: push
prereq[0]ontograph[prereq[1]], because the course in position 1 comes first. - Count the dependency: add 1 to
inDegree[prereq[0]]. - Create
queueas an empty array for the courses that can be taken now. - Scan every course with a
forloop and push the ones whoseinDegreeis 0. If there are none, every course waits for another one. - Start
takenat 0. It counts the courses taken and doubles as the index of the next course to take from the queue. Nothing is ever removed from the array: the entries beforetakenare already taken. - Loop while
taken < queue.length. The queue grows while the loop runs, and the loop ends when every course that joined it has been taken. - Read
queue[taken]intocourse, then add 1 totaken. - Visit the courses waiting for it: loop over
graph[course], subtract 1 from eachinDegree[nextCourse], and pushnextCourseonto the queue when the count reaches 0. A count reaches 0 only once, so each course enters the queue at most once. - Return
taken === numCourses.
The solution in JavaScript
class Solution {
canFinish(numCourses, prerequisites) {
const graph = Array.from({length: numCourses}, () => []);
const inDegree = new Array(numCourses).fill(0);
for (const prereq of prerequisites) {
graph[prereq[1]].push(prereq[0]);
inDegree[prereq[0]]++;
}
const queue = [];
for (let course = 0; course < numCourses; course++) {
if (inDegree[course] === 0) {
queue.push(course);
}
}
let taken = 0;
while (taken < queue.length) {
const course = queue[taken];
taken++;
for (const nextCourse of graph[course]) {
inDegree[nextCourse]--;
if (inDegree[nextCourse] === 0) {
queue.push(nextCourse);
}
}
}
return taken === numCourses;
}
}
Some JavaScript details worth knowing:
Array.fromversusfillfor the graph.new Array(3).fill([])puts the same array at all three positions. Aftersh[0].push(1)on such an array, printing it withJSON.stringifygives[[1],[1],[1]].Array.fromwith a callback runs the callback per index and builds separate arrays. ForinDegree,fill(0)is fine because numbers are copied by value.- A queue without
shift. JavaScript has no built-in queue type. Callingqueue.shift()works, but it removes the first element and moves the others down. Reading with an index, as here, keeps every step constant-time and leaves the queue intact, which is whytakencan be compared withnumCoursesat the end. for...ofversusfor...in.for (const nextCourse of graph[course])gives the values.for...inwould give the indices as strings.++and--on array elements.inDegree[nextCourse]--changes the element in place.
Complexity
Time: O(V + E), with V courses and E pairs. Building the graph touches each pair once. Each course enters the queue at most once, and when it is taken its list is scanned once, so every arrow is looked at once overall.
Space: O(V + E) for the graph, the in-degree array and the queue. The adjacency lists hold one entry per pair.
Edge cases and common mistakes
- No prerequisites. With
numCourses = 3andprerequisites = [], every course starts in the queue and the answer istrue. - Reversed arrows. In
[a, b],bcomes first. Buildinggraph[a]instead ofgraph[b]would turn the problem around and count the wrong in-degrees. - Cycles away from the start. With
numCourses = 4and[[1, 0], [2, 1], [1, 2]], course 0 is free, but courses 1 and 2 wait for each other and course 3 is free too. Only 0 and 3 are taken, so the answer isfalse. Checking only that some course starts at 0 is not enough. - Cycle of every course. With
[[1, 0], [2, 1], [0, 2]]and 3 courses, nothing has an in-degree of 0 and the queue starts empty, so the loop never runs and0 === 3is false. - Returning
truewhen the queue empties. The queue always empties eventually. The answer depends on whether all courses went through it. - Recursion depth. A recursive depth-first search for cycles on a chain of 100,000 courses can overflow the call stack. Kahn's algorithm uses loops only: a chain of 100,000 courses returns
true.
Testing
numCourses = 2,prerequisites = [[1, 0]]givestrue.numCourses = 2,prerequisites = [[1, 0], [0, 1]]givesfalse.numCourses = 4,prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]givestrue.numCourses = 3,prerequisites = [[1, 0], [2, 1], [0, 2]]givesfalse.numCourses = 4,prerequisites = [[1, 0], [2, 1], [1, 2]]givesfalse.numCourses = 1,prerequisites = []givestrue.
