Course Schedule
The problem
Section titled “The problem”There are numCourses courses numbered 0 to numCourses - 1. Each pair [a, b] means
you must take course b before course a. Return true if you can finish every course.
numCourses = 2, prerequisites = [[1, 0], [0, 1]] -> false(1 needs 0, and 0 needs 1: neither can go first)Key insight
Section titled “Key insight”Draw an edge from each prerequisite to the course it unlocks. You can finish everything exactly when this directed graph has no cycle.
Kahn’s algorithm checks this with BFS. Count each course’s indegree (number of
unmet prerequisites). Courses with indegree 0 can be taken now, so queue them. Taking a
course removes one prerequisite from each course it unlocks; when one hits 0, queue it.
If you manage to take all numCourses, there is no cycle. Courses on a cycle never reach
indegree 0, so they are never taken.
The other classic is DFS with 3 colors: unvisited, in the current path, done. Reaching a node that is “in the current path” means a cycle. It is also O(V + E), but more code.
Show solutionHide solution
from collections import deque
def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool: graph = [[] for _ in range(num_courses)] # prereq -> courses it unlocks indegree = [0] * num_courses for course, prereq in prerequisites: graph[prereq].append(course) indegree[course] += 1
queue = deque(i for i in range(num_courses) if indegree[i] == 0) taken = 0 while queue: course = queue.popleft() taken += 1 for nxt in graph[course]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return taken == num_courses # anything left over is stuck in a cycleexport function canFinish(numCourses: number, prerequisites: number[][]): boolean { const graph: number[][] = Array.from({ length: numCourses }, () => []); // prereq -> courses it unlocks const indegree: number[] = new Array(numCourses).fill(0); for (const [course, prereq] of prerequisites) { graph[prereq].push(course); indegree[course]++; }
// Array + head index instead of shift(), which is O(n) per call. const queue: number[] = []; for (let i = 0; i < numCourses; i++) if (indegree[i] === 0) queue.push(i); let head = 0; let taken = 0; while (head < queue.length) { const course = queue[head++]; taken++; for (const next of graph[course]) { if (--indegree[next] === 0) queue.push(next); } } return taken === numCourses; // anything left over is stuck in a cycle}import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { List<List<Integer>> graph = new ArrayList<>(); // prereq -> courses it unlocks for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>()); int[] indegree = new int[numCourses]; for (int[] p : prerequisites) { graph.get(p[1]).add(p[0]); indegree[p[0]]++; }
Queue<Integer> queue = new ArrayDeque<>(); for (int i = 0; i < numCourses; i++) if (indegree[i] == 0) queue.add(i); int taken = 0; while (!queue.isEmpty()) { int course = queue.poll(); taken++; for (int next : graph.get(course)) { if (--indegree[next] == 0) queue.add(next); } } return taken == numCourses; // anything left over is stuck in a cycle }}Complexity
Section titled “Complexity”- Time: O(V + E) — building the graph is O(E); each course is queued once and each edge is relaxed once.
- Space: O(V + E) — adjacency lists plus the indegree array and queue.
Watch out for
Section titled “Watch out for”- Edge direction.
[a, b]meansb -> a. Reversing it still gives the right yes/no answer here, but gets Course Schedule II wrong. - Compare the count, not the queue. The algorithm ends with an empty queue in both
cases; check that
taken == numCourses. - Self-dependency (
[0, 0]) and disconnected parts. A cycle can hide in a component that has no link to the others, so process every course, not only one start. - Courses with no prerequisites have indegree 0 and must be seeded into the queue.
Variations
Section titled “Variations”Course Schedule II (LeetCode 210)
Section titled “Course Schedule II (LeetCode 210)”Return an order to take the courses, or an empty list if impossible. The trick:
the same Kahn’s algorithm; append each course to the result as you pop it. If the result
is shorter than numCourses, return empty.
Find Eventual Safe States (LeetCode 802)
Section titled “Find Eventual Safe States (LeetCode 802)”Find all nodes from which every path ends at a terminal node (none leads into a cycle). The trick: run Kahn’s algorithm on the reversed graph, starting from terminal nodes. Every node it reaches is safe.
Course Schedule IV (LeetCode 1462)
Section titled “Course Schedule IV (LeetCode 1462)”Answer queries “is course a a prerequisite of b?” (directly or indirectly). The
trick: compute reachability between all pairs, by DFS from each node or Floyd-Warshall,
then answer each query by lookup.