Course Schedule II
LeetCode 210 · Medium · solution, intuition & step-by-step walkthrough
DFS post-order, reversed = topological order.
This is how I solved Course Schedule II (LeetCode 210), a medium problem from the Topological Sort / DAG pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same cycle detection, but now record each node after all its dependants are finished. Reversing that finishing order gives a valid order to take the courses (a topological sort).
Approach
- 1
DFS with path markers; cycle → [].
- 2
Append each node to the stack when its DFS finishes.
- 3
Return the stack reversed.
How I solved it
DFS topological sortPythonO(V+E) time
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj = defaultdict(list)
for v,u in prerequisites:
adj[u].append(v)
path_visited = [False]*numCourses
visited = set()
stack = []
def dfs(node):
visited.add(node)
path_visited[node]=1
for adj_node in adj[node]:
if adj_node not in visited:
if dfs(adj_node): #has cycle
return True
elif path_visited[adj_node]==1: #already visited in the current path
return True
#before coming back
stack.append(node)
path_visited[node]=0
return False
for node in range(numCourses):
if node not in visited:
if dfs(node): #has cycle
return []
return stack[::-1]Course Schedule II — FAQ
What is the intuition behind Course Schedule II?
Same cycle detection, but now record each node after all its dependants are finished. Reversing that finishing order gives a valid order to take the courses (a topological sort).
How do you solve Course Schedule II (LeetCode 210)?
1. DFS with path markers; cycle → []. 2. Append each node to the stack when its DFS finishes. 3. Return the stack reversed.
What is the time and space complexity of Course Schedule II?
Time: O(V + E). Space: O(V + E). (Accepted approach: DFS topological sort.)
What are common mistakes in Course Schedule II?
Many orders are valid — any topological order is accepted.