LeetCode 207: Course Schedule is a Medium graph general problem. This Python walkthrough develops a Kahn topological sort solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Graph General |
| Reusable pattern | Kahn topological sort |
| Complexity | O(V+E) time and O(V+E) space |
Recognizing the pattern
Graph traversal separates reachability from representation: adjacency describes possible moves, while a visited structure prevents repeated work.
For this problem specifically, count prerequisites as indegrees, repeatedly remove zero-indegree courses, and reduce the indegrees of dependent courses. The invariant worth writing beside the code is: The queue contains exactly the currently schedulable courses with no remaining prerequisites.
Step-by-step algorithm
- Identify the input state consumed by
canFinish(numCourses, prerequisites)and initialize the data required by the Kahn topological sort pattern. - Count prerequisites as indegrees, repeatedly remove zero-indegree courses, and reduce the indegrees of dependent courses.
- After each update, verify the page’s central invariant: The queue contains exactly the currently schedulable courses with no remaining prerequisites.
- Finish only after the boundary behavior is covered: Processing fewer than all courses proves a directed cycle.
Python solution
from collections import deque
class Solution:
def canFinish(self, numCourses, prerequisites):
graph = [[] for _ in range(numCourses)]; indegree = [0] * numCourses
for course, prerequisite in prerequisites:
graph[prerequisite].append(course); indegree[course] += 1
queue = deque(i for i, degree in enumerate(indegree) if degree == 0)
completed = 0
while queue:
course = queue.popleft(); completed += 1
for following in graph[course]:
indegree[following] -= 1
if indegree[following] == 0: queue.append(following)
return completed == numCoursesReading the implementation
The main entry point is canFinish(numCourses, prerequisites). The named working state includes graph, queue, completed, course; those variables make the Kahn topological sort state visible instead of hiding it in incidental control flow.
The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, count prerequisites as indegrees, repeatedly remove zero-indegree courses, and reduce the indegrees of dependent courses.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Count prerequisites as indegrees, repeatedly remove zero-indegree courses, and reduce the indegrees of dependent courses. Each update records the current item without invalidating earlier decisions; consequently, the queue contains exactly the currently schedulable courses with no remaining prerequisites.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(V+E) time and O(V+E) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
DFS and BFS often have the same asymptotic cost; choose DFS for recursive structure and BFS when distance or processing order matters. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().canFinish(2,[[1,0]]) and not Solution().canFinish(2,[[1,0],[0,1]])Common mistakes and edge cases
- Problem-specific boundary: Processing fewer than all courses proves a directed cycle.
- Pattern-level pitfall: Mark a state when it is discovered rather than after all of its neighbors are processed, or cycles can enqueue it repeatedly.
- Invariant check: after every update, confirm that the queue contains exactly the currently schedulable courses with no remaining prerequisites.
Interview review checklist
- Explain why Kahn topological sort matches the structure of this input.
- State the invariant in one sentence before tracing code: The queue contains exactly the currently schedulable courses with no remaining prerequisites.
- Derive O(V+E) time and O(V+E) space from how many times each element or state is visited.
- Test the boundary explicitly: Processing fewer than all courses proves a directed cycle.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 399. Evaluate Division · Next: 210. Course Schedule II