Course Schedule II (LeetCode 210): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Graph
Topological Sort

You have numCourses courses and a list of pairs saying that one course must be taken before another. Return any order in which you can finish every course, or an empty list if the prerequisites contain a cycle that makes finishing impossible.

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

Intuition

Think of each course as a node and each prerequisite pair [a, b] as a directed edge from b to a, meaning b must come first. A valid schedule is then exactly a topological ordering of this graph, and one exists if and only if the graph has no cycle. That reframing is most of the work.

A naive approach would repeatedly scan all courses looking for one whose prerequisites are all done, take it, and repeat. Each scan is O(V + E), and you do V of them, so it is quadratic. The observation that speeds this up is that you only need to know how many unfinished prerequisites each course still has. That number is the course's in-degree. When you finish a course, only its direct dependents can change, so you decrement their in-degrees and immediately notice any that drop to zero.

This is Kahn's algorithm. Keep a queue of courses with in-degree zero, since they are ready to take now. Pop one, append it to the schedule, and release its dependents. If a cycle exists, the courses on it never reach in-degree zero, so they never enter the queue, and the final schedule comes up short. Checking the length of the result is therefore all the cycle detection you need.

Approach: Kahn's algorithm (BFS topological sort)

  1. Build an adjacency list graph where graph[prereq] lists the courses that depend on it, and an indegree array counting each course's prerequisites.
  2. For each pair [course, prereq], append course to graph[prereq] and increment indegree[course].
  3. Seed a deque with every course whose in-degree is 0.
  4. While the queue is non-empty, pop a course and append it to result.
  5. For each dependent of that course, decrement its in-degree and push it once the in-degree reaches 0.
  6. Return result if it contains all numCourses courses; otherwise a cycle blocked some courses, so return an empty list.

Step-by-step example

numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
  1. The graph becomes 0 → [1, 2], 1 → [3] and 2 → [3], and the in-degrees are [0, 1, 1, 2].
  2. Only course 0 has in-degree 0, so the queue starts as [0].
  3. Pop 0 and add it to the result. Courses 1 and 2 drop to in-degree 0 and are queued.
  4. Pop 1. Course 3 drops from 2 to 1, which is not zero yet, so nothing is queued.
  5. Pop 2. Course 3 drops to 0 and is queued. Pop 3, and the result [0, 1, 2, 3] has length 4, so it is returned.

Code: Python, Java, C++

1class Solution:
2    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
3        graph = defaultdict(list)
4        indegree = [0] * numCourses
5
6        for course, prereq in prerequisites:
7            graph[prereq].append(course)
8            indegree[course] += 1
9
10        queue = deque([i for i in range(numCourses) if indegree[i] == 0])
11        result = []
12
13        while queue:
14            course = queue.popleft()
15            result.append(course)
16            for next_course in graph[course]:
17                indegree[next_course] -= 1
18                if indegree[next_course] == 0:
19                    queue.append(next_course)
20
21        return result if len(result) == numCourses else []

Time and space complexity

Time

O(V + E)

Building the graph touches each prerequisite pair once. During the search each course is enqueued and dequeued at most once, and each edge is followed exactly once when its source course is popped, where V is numCourses and E is the number of pairs.

Space

O(V + E)

The adjacency list stores every edge, and the in-degree array, queue and result each hold at most V entries.

Other approaches

DFS with three-color cycle detection (time O(V + E), space O(V + E))

Run DFS from every unvisited course, marking nodes as visiting and then done. A back edge to a visiting node means a cycle. Appending each node when it finishes yields a reverse topological order, so you reverse it at the end, or build the edges in the opposite direction.

Common mistakes

  • Pointing the edges the wrong way. The pair [a, b] means b comes before a, so the edge is b → a. Reversing it produces an order that is backwards.
  • Returning the partial result when a cycle exists. The problem wants an empty list, so you must compare len(result) with numCourses.
  • Forgetting courses that appear in no pair at all. They have in-degree 0 and must be seeded into the queue too, which the list comprehension over range(numCourses) handles.
  • Using a plain list and pop(0) for the queue. That works but costs O(V) per pop; a deque keeps each pop O(1).

Frequently asked questions

How is Course Schedule II different from Course Schedule?

The first version only asks whether all courses can be finished, which is a yes or no cycle check. This version asks you to return an actual valid ordering. The same Kahn's algorithm solves both; here you keep the order you pop courses in.

Is the answer to Course Schedule II unique?

No. Whenever two or more courses are ready at the same time, either can go first, so many orders can be valid. Any topological order is accepted.

BFS or DFS for topological sort?

Both run in O(V + E). Kahn's BFS is iterative, makes cycle detection a simple length check, and avoids deep recursion. DFS is just as correct but needs careful state tracking and a reversal step.

How does Kahn's algorithm detect a cycle?

Nodes on a cycle always have at least one incoming edge from another node on the same cycle, so their in-degree never reaches zero. They never get processed, and the result ends up with fewer than V nodes.