Skip to content

Course Schedule

MediumLeetCode #207Time O(V + E)Space O(V + E)

There are numCourses courses numbered 0 to numCourses - 1. Each pair [a, b] means you must take course b before course a. Return true if you can finish every course.

numCourses = 2, prerequisites = [[1, 0], [0, 1]] -> false
(1 needs 0, and 0 needs 1: neither can go first)

Draw an edge from each prerequisite to the course it unlocks. You can finish everything exactly when this directed graph has no cycle.

Kahn’s algorithm checks this with BFS. Count each course’s indegree (number of unmet prerequisites). Courses with indegree 0 can be taken now, so queue them. Taking a course removes one prerequisite from each course it unlocks; when one hits 0, queue it. If you manage to take all numCourses, there is no cycle. Courses on a cycle never reach indegree 0, so they are never taken.

The other classic is DFS with 3 colors: unvisited, in the current path, done. Reaching a node that is “in the current path” means a cycle. It is also O(V + E), but more code.

Show solutionHide solution
from collections import deque
def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
graph = [[] for _ in range(num_courses)] # prereq -> courses it unlocks
indegree = [0] * num_courses
for course, prereq in prerequisites:
graph[prereq].append(course)
indegree[course] += 1
queue = deque(i for i in range(num_courses) if indegree[i] == 0)
taken = 0
while queue:
course = queue.popleft()
taken += 1
for nxt in graph[course]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return taken == num_courses # anything left over is stuck in a cycle
  • Time: O(V + E) — building the graph is O(E); each course is queued once and each edge is relaxed once.
  • Space: O(V + E) — adjacency lists plus the indegree array and queue.
  • Edge direction. [a, b] means b -> a. Reversing it still gives the right yes/no answer here, but gets Course Schedule II wrong.
  • Compare the count, not the queue. The algorithm ends with an empty queue in both cases; check that taken == numCourses.
  • Self-dependency ([0, 0]) and disconnected parts. A cycle can hide in a component that has no link to the others, so process every course, not only one start.
  • Courses with no prerequisites have indegree 0 and must be seeded into the queue.

Return an order to take the courses, or an empty list if impossible. The trick: the same Kahn’s algorithm; append each course to the result as you pop it. If the result is shorter than numCourses, return empty.

Find all nodes from which every path ends at a terminal node (none leads into a cycle). The trick: run Kahn’s algorithm on the reversed graph, starting from terminal nodes. Every node it reaches is safe.

Answer queries “is course a a prerequisite of b?” (directly or indirectly). The trick: compute reachability between all pairs, by DFS from each node or Floyd-Warshall, then answer each query by lookup.