Problem overview
There are numCourses courses labeled 0 to numCourses - 1. Each pair [a, b] in prerequisites means course b must be taken before course a. The method canFinish 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]], course 0 needs nothing and course 1 needs course 0, so the order 0, 1 works and the answer is true. With [[1, 0], [0, 1]] each course waits for the other, so neither can ever be taken and the answer is false.
It helps to 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. Such an order exists exactly when the arrows contain no cycle, so the question is really "does this graph have a cycle?"
Approach: take free courses and remove their arrows
Think of how you would plan the courses by hand. Start with the courses that have no prerequisites. Taking one of them removes it as a requirement for others, and some of those may now be free. Keep going until nothing is free. If you took every course, the plan works. If some courses are left, each of them still waits for another one that was never taken, which can only happen when they wait on each other in a cycle, or on a course that does.
This is Kahn's algorithm. It needs two things per course: the list of courses that wait for it, and the count of its prerequisites not yet taken, called the in-degree (the number of arrows pointing into the course). A course is free when its count reaches 0. Each pair is looked at a constant number of times, so the work is O(V + E) for V courses and E pairs, which fits the limits of 100,000 each.
A depth-first search that looks for cycles also works. Kahn's algorithm avoids recursion, which matters here: a chain of 100,000 courses would make a recursive search go 100,000 calls deep.
Step by step
- Build the graph.
graph[b]holds the courses that wait for courseb.Array.from({length: numCourses}, () => [])runs the arrow function once per course, so each course gets its own array. - Create
inDegree, an array of zeros.inDegree[a]counts the prerequisites of courseathat are not taken yet. - Loop over the pairs. For each pair, push
prereq[0]ontograph[prereq[1]](courseprereq[0]waits forprereq[1]) and add 1 toinDegree[prereq[0]]. - Create the queue of courses that can be taken now, and fill it with every course whose in-degree is 0. If there are none, every course waits for another, and nothing can start.
- Keep a counter,
taken. It counts the courses taken so far and is also the position of the next course to take inqueue. Nothing is ever removed from the queue: reading by index avoidsshift(), which moves every remaining element. - Loop while
taken < queue.length. The queue grows as courses become free, and the loop ends when every course that joined it has been taken. - Take a course: read
queue[taken]and incrementtaken. - Release the courses that wait for it. For each
nextCourseingraph[course], decrement its in-degree. When it reaches 0 its last prerequisite has just been taken, so push it onto the queue. A count hits 0 only once, so each course enters the queue at most once. - Return
taken === numCourses. Courses on a cycle never reach 0, and neither does any course that needs one of them, so they are never taken.
The solution in TypeScript
class Solution {
canFinish(numCourses: number, prerequisites: number[][]): boolean {
const graph: number[][] = Array.from({length: numCourses}, () => []);
const inDegree: number[] = new Array(numCourses).fill(0);
for (const prereq of prerequisites) {
graph[prereq[1]].push(prereq[0]);
inDegree[prereq[0]]++;
}
const queue: number[] = [];
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;
}
}
For the third example, numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], only course 0 starts free. Taking it frees 1 and 2, and taking those frees 3. The final queue is [0, 1, 2, 3], taken is 4, and the method returns true. For the cyclic example [[1, 0], [0, 1]] the queue stays empty, taken is 0 and the result is false. With numCourses = 3 and [[1, 0], [2, 1], [1, 2]], course 0 is taken, but courses 1 and 2 wait for each other: the queue is [0], taken is 1 and the result is false.
Some TypeScript details:
- Why not
new Array(numCourses).fill([])?fillstores the same array object in every slot. Aftershared[0].push(7)on such an array of three slots, it prints as[[7],[7],[7]]. WithArray.from(..., () => [])the same push gives[[7],[],[]]. Filling with0is fine because numbers are copied by value. - Types are erased.
number[][]checks nothing at run time. The compiler uses it to know thatgraph[b]is an array of numbers. ===in the checks.inDegree[course] === 0andtaken === numCoursescompare numbers without any conversion.for...ofversusfor.for...ofreads the values, which is what the pair and neighbour loops need. The loop over courses needs the index itself, so it uses a counter.- Reading a growing array. The
whilecondition re-readsqueue.lengthon every turn, so the pushes made inside the loop extend it.
Complexity
Time: O(V + E). Building the graph touches each pair once. Each course enters the queue at most once and is taken once, and when it is taken its list of waiting courses is scanned once. Over the whole run, every pair is scanned exactly once.
Space: O(V + E). graph holds one array per course and one entry per pair, and inDegree and queue hold at most one number per course.
Edge cases and common mistakes
- No prerequisites.
canFinish(3, [])returnstrue: all three courses start in the queue, andtakenreaches 3. - A single course.
canFinish(1, [])returnstrue. - Swapping the pair. The pair
[a, b]meansbcomes first. Usingprereq[0]as the key ofgraphand incrementinginDegree[prereq[1]]reverses every arrow. It still answers the cycle question correctly, but the order it describes is backwards, so check the direction when you extend the code. - Counting the wrong thing at the end. Returning whether
queueis empty, or checking only the courses that started free, misses courses stuck behind a cycle. Compare the number of courses taken withnumCourses. - Using
shift()for the queue. It works, but it moves every remaining element, so a long queue gets slow. The indextakenavoids that. - Cycles that don't touch every course. In the 3-course example above, course 0 is fine and the answer is still
false: one cycle anywhere is enough. - A long chain. With 100,000 courses in a line,
[i, i - 1]for everyifrom 1 to 99999, the method returnstrueand the queue ends up with all 100,000 courses.
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], [1, 2]]givesfalse.numCourses = 3,prerequisites = []givestrue.
