Course Schedule (LeetCode 207): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Graph
Topological Sort

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Build preMap, mapping each course to the list of its prerequisites.
  2. Keep visitSet, the set of courses on the current DFS path.
  3. In dfs(crs), return False if crs is already in visitSet, because that means a cycle. Return True if its prerequisite list is empty.
  4. Add crs to visitSet and call dfs on every prerequisite, returning False as soon as one fails.
  5. Remove crs from visitSet and set preMap[crs] = [] so future calls know it is completable without exploring again.
  6. Run dfs on 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]]
  1. The map is {0: [], 1: [0], 2: [0], 3: [1, 2]}. Course 0 has no prerequisites, so dfs(0) returns True right away.
  2. 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.
  3. dfs(3) puts 3 on the path. Its prerequisites 1 and 2 now have empty lists, so both return True without further exploration.
  4. Course 3 is cleared too, every course succeeds, and the answer is True.
  5. 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 in visitSet, 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 True

Time and space complexity

Time

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.

Space

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.