Problem
There are numCourses labeled from 0 to numCourses-1, and a list of prerequisites [a, b] meaning b must be taken before a. Return true if you can finish all courses.
Original: LeetCode 207: Course Schedule.
Examples
Example 1
`numCourses = 2, prerequisites = [[1, 0]]``true`Take course 0, then course 1.
Example 2
`numCourses = 2, prerequisites = [[1, 0], [0, 1]]``false`Each course needs the other first: a cycle.
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses- All the pairs prerequisites[i] are unique.
Hints
Hint 1
The graph is directed. A cycle such as 0 requires 1 and 1 requires 0 makes completion impossible.
Hint 2
Prerequisite constraints are a topological sort. Kahn's algorithm or a DFS color mark both detect cycles.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Trying every permutation of courses is factorial and unnecessary.
Optimal. Kahn's algorithm: repeatedly take a node with indegree 0. If the count of taken nodes equals numCourses, there is no cycle.
Alternative. DFS with three colors (unvisited, in the current path, done) returns false as soon as you see a back edge.
Complexity
- Time
- O(V + E)
O(V + E) time and O(V + E) space, where V is numCourses and E is the number of prerequisites.
- Space
- O(V + E)
Code
from collections import defaultdict, deque
def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
graph = defaultdict(list)
indeg = [0] * num_courses
for a, b in prerequisites:
graph[b].append(a)
indeg[a] += 1
q = deque(i for i in range(num_courses) if indeg[i] == 0)
taken = 0
while q:
u = q.popleft()
taken += 1
for v in graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return taken == num_courses
if __name__ == "__main__":
assert can_finish(2, [[1, 0]]) is True
assert can_finish(2, [[1, 0], [0, 1]]) is False
print("ok")import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class CourseSchedule {
static boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indeg = new int[numCourses];
for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());
for (int[] p : prerequisites) {
graph.get(p[1]).add(p[0]);
indeg[p[0]]++;
}
var q = new ArrayDeque<Integer>();
for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.add(i);
int taken = 0;
while (!q.isEmpty()) {
int u = q.remove();
taken++;
for (int v : graph.get(u)) if (--indeg[v] == 0) q.add(v);
}
return taken == numCourses;
}
public static void main(String[] args) {
if (!canFinish(2, new int[][] {{1, 0}})) throw new AssertionError();
if (canFinish(2, new int[][] {{1, 0}, {0, 1}})) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: two courses with [[1,0]] can be finished; [[1,0],[0,1]] cannot.
- Courses with no prerequisites start with indegree 0 and can be taken immediately.
- A self-loop is a cycle.
Follow-ups
- Course Schedule II asks for one valid order, which is the sequence Kahn's algorithm already produces.
Interview script
"Prerequisites form a directed graph, and I can finish if and only if that graph is acyclic. I run Kahn's algorithm: repeatedly take a course whose prerequisites are already done. If some courses are left, there is a cycle."
Source: LeetCode 207: Course Schedule
Sources (1)
- LeetCode 207: Course Scheduleleetcode.com