Course Schedule
Difficulty: Medium
There are numCourses courses, labeled 0 to numCourses - 1. You're given prerequisite pairs [a, b], each meaning "finish course b before taking course a."
Return whether you can finish all the courses.
Examples
Input: numCourses = 2, prerequisites = [[1, 0]]
Output: true
Take course 0 first, then course 1. No conflict.
Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Output: false
Course 1 needs course 0 first, but course 0 needs course 1 first - neither can ever go first.
Input: numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: true
One valid order is 0, 1, 2, 3 - course 0 has no prerequisites, and every later course's prerequisites come before it.
Constraints
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
There are no duplicate prerequisite pairs.
Approach
Build a directed graph with an edge from b to a ("b before a"). You can finish all courses exactly when the graph has no cycle. On a cycle, every course waits for another course on the same cycle.
To find a cycle, run a DFS that tracks each node's state:
- unvisited
- visiting: on the current recursion path
- done: confirmed cycle-free
If the DFS reaches a visiting node, that's a back-edge into the current path: a cycle, so return false. If it explores every node without that happening, return true.
A non-recursive alternative is Kahn's algorithm: repeatedly remove courses with no remaining prerequisites. If every course gets removed, there's no cycle.
Solutions
Brute Force - Try Every Ordering
You can finish exactly when some ordering respects every prerequisite. The naive check generates every ordering and tests it against every pair, stopping at the first one that works.
function canFinish(numCourses, prerequisites) {
const courses = Array.from({ length: numCourses }, (_, i) => i);
function isValidOrder(order) {
const position = new Map();
order.forEach((course, index) => position.set(course, index));
for (const [a, b] of prerequisites) {
if (position.get(b) > position.get(a)) return false; // b must come before a
}
return true;
}
function permute(start) {
if (start === courses.length) {
return isValidOrder(courses);
}
for (let i = start; i < courses.length; i++) {
[courses[start], courses[i]] = [courses[i], courses[start]];
if (permute(start + 1)) return true;
[courses[start], courses[i]] = [courses[i], courses[start]];
}
return false;
}
return permute(0);
}Time: O(n! × (n + p)) - n! orderings, each checked against p prerequisite pairs · Space: O(n)
Optimal - DFS Cycle Detection
Build an adjacency list, then DFS from every course. Tag each node visiting (on the current path) or done (fully explored, no cycle). Reaching a visiting node means a cycle, so finishing is impossible.
function canFinish(numCourses, prerequisites) {
const graph = Array.from({ length: numCourses }, () => []);
for (const [a, b] of prerequisites) {
graph[b].push(a); // b must be taken before a
}
const UNVISITED = 0, VISITING = 1, DONE = 2;
const state = new Array(numCourses).fill(UNVISITED);
function hasCycle(course) {
if (state[course] === VISITING) return true; // back edge into current path
if (state[course] === DONE) return false; // already confirmed safe
state[course] = VISITING;
for (const next of graph[course]) {
if (hasCycle(next)) return true;
}
state[course] = DONE;
return false;
}
for (let course = 0; course < numCourses; course++) {
if (hasCycle(course)) return false;
}
return true;
}Time: O(V + E) - every course and every prerequisite edge is visited once · Space: O(V + E) for the adjacency list, plus O(V) for the state array and recursion stack