Course Schedule (LeetCode 207): Solution and Explanation
There are numCourses courses labeled from 0, and each prerequisite pair [a, b] says you must take course b before course a. Decide whether it is possible to finish every course. That is true exactly when the prerequisites contain no circular dependency.
Watch it run step by step
Try your own input and write the code →Intuition
Model the courses as a directed graph with an edge from each course to each of its prerequisites. A course can be completed only if every chain of prerequisites below it eventually reaches courses with none. The only thing that can stop that is a cycle, such as course 0 needing 1, 1 needing 2 and 2 needing 0. So the real question is whether this directed graph contains a cycle.
Depth-first search detects cycles in a directed graph by tracking the current path. When you start exploring a course, put it on the path. If while following prerequisites you reach a course that is already on the path, you have walked in a circle. When you finish exploring a course without finding a cycle, take it off the path, since other courses may legitimately depend on it through a different route.
Without memoization, the same course could be explored again and again from different starting points, which can blow up the running time. The reference code uses a neat trick: once a course is proven completable, it clears that course's prerequisite list. Any later call sees an empty list and returns True immediately. That way each course and each edge is fully explored at most once, giving linear time overall.
Approach: DFS cycle detection with memoization
- Build
preMap, mapping each course to the list of its prerequisites. - Keep
visitSet, the set of courses on the current DFS path. - In
dfs(crs), return False ifcrsis already invisitSet, because that means a cycle. Return True if its prerequisite list is empty. - Add
crstovisitSetand calldfson every prerequisite, returning False as soon as one fails. - Remove
crsfromvisitSetand setpreMap[crs] = []so future calls know it is completable without exploring again. - Run
dfson every course, since the graph may have several disconnected parts, and return True if none of them finds a cycle.
Step-by-step example
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
- The map is {0: [], 1: [0], 2: [0], 3: [1, 2]}. Course 0 has no prerequisites, so
dfs(0)returns True right away. dfs(1)puts 1 on the path, finds that course 0 is completable, removes 1 from the path and clears its list. Course 2 goes the same way.dfs(3)puts 3 on the path. Its prerequisites 1 and 2 now have empty lists, so both return True without further exploration.- Course 3 is cleared too, every course succeeds, and the answer is True.
- If the input were [[1,0],[2,1],[0,2]] with three courses,
dfs(0)would follow 0 to 2 to 1 and back to 0, find 0 invisitSet, and return False.
Code: Python, Java, C++
1class Solution:
2 def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
3 preMap = { i:[] for i in range(numCourses) }
4 for crs, pre in prerequisites:
5 preMap[crs].append(pre)
6
7 visitSet = set()
8
9 def dfs(crs):
10 if crs in visitSet:
11 return False
12 if preMap[crs] == []:
13 return True
14
15 visitSet.add(crs)
16 for pre in preMap[crs]:
17 if not dfs(pre): return False
18 visitSet.remove(crs)
19 preMap[crs] = []
20 return True
21
22 for crs in range(numCourses):
23 if not dfs(crs): return False
24 return True1class Solution {
2 public boolean canFinish(int numCourses, int[][] prerequisites) {
3 ArrayList<Integer>[] adj = new ArrayList[numCourses];
4 for (int i = 0; i < numCourses; i++) adj[i] = new ArrayList<>();
5 for (int[] pre : prerequisites) adj[pre[0]].add(pre[1]);
6
7 int[] visit = new int[numCourses]; // 0=unvisited, 1=visiting, 2=visited
8
9 for (int i = 0; i < numCourses; i++) {
10 if (dfs(i, adj, visit)) return false;
11 }
12 return true;
13 }
14
15 private boolean dfs(int curr, ArrayList<Integer>[] adj, int[] visit) {
16 if (visit[curr] == 1) return true; // Cycle
17 if (visit[curr] == 2) return false;
18
19 visit[curr] = 1;
20 for (int next : adj[curr]) {
21 if (dfs(next, adj, visit)) return true;
22 }
23 visit[curr] = 2;
24 return false;
25 }
26}1class Solution {
2public:
3 bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
4 vector<vector<int>> adj(numCourses);
5 for (auto& pre : prerequisites) adj[pre[0]].push_back(pre[1]);
6
7 vector<int> visit(numCourses, 0); // 0=unvisited, 1=visiting, 2=visited
8
9 for (int i = 0; i < numCourses; i++) {
10 if (dfs(i, adj, visit)) return false;
11 }
12 return true;
13 }
14
15 bool dfs(int curr, vector<vector<int>>& adj, vector<int>& visit) {
16 if (visit[curr] == 1) return true;
17 if (visit[curr] == 2) return false;
18
19 visit[curr] = 1;
20 for (int next : adj[curr]) {
21 if (dfs(next, adj, visit)) return true;
22 }
23 visit[curr] = 2;
24 return false;
25 }
26};Time and space complexity
O(V + E)
V is the number of courses and E the number of prerequisite pairs. Building the map takes O(V + E), and thanks to the cleared lists each course is fully expanded once, following each edge once.
O(V + E)
The adjacency map stores every edge, and the visit set and recursion stack can each hold up to V courses on a long chain.
Other approaches
Kahn's algorithm (BFS topological sort) (time O(V + E), space O(V + E))
Count each course's incoming prerequisites, start a queue with every course whose count is 0, and repeatedly take a course and decrement the counts of courses that depend on it. If the number of processed courses equals numCourses, there is no cycle. It avoids recursion and naturally produces a valid order.
Three-color DFS (time O(V + E), space O(V + E))
Mark each course as unvisited, visiting or done. Reaching a visiting course means a cycle, and done courses are skipped. It is the textbook version of the same idea and does not modify the adjacency map.
Common mistakes
- Using a single visited set that is never cleared after a course finishes. A course reached by two different paths then looks like a cycle even when it is not.
- Forgetting to memoize completed courses, which can cause exponential re-exploration on dense graphs.
- Only starting the DFS from course 0. Disconnected groups of courses can contain their own cycles.
- Reversing the meaning of
[a, b]. It means b must come before a, though either direction finds the same cycles as long as you are consistent.
Frequently asked questions
Why is Course Schedule a cycle detection problem?
A course can be taken once its prerequisites are done. If the dependencies form a loop, no course in that loop can ever go first, so all courses can be finished exactly when the prerequisite graph has no cycle.
BFS or DFS for Course Schedule?
Both run in O(V + E). Kahn's BFS algorithm is iterative and also yields a valid course order, while DFS with a path set is compact and detects the cycle directly.
How do you return the actual course order?
That is the follow-up problem. Record each course when its DFS finishes, or record the order in which Kahn's algorithm removes courses, and return an empty list if a cycle is found.