Course Schedule II (LeetCode 210): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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)
- Build an adjacency list
graphwheregraph[prereq]lists the courses that depend on it, and anindegreearray counting each course's prerequisites. - For each pair
[course, prereq], appendcoursetograph[prereq]and incrementindegree[course]. - Seed a deque with every course whose in-degree is 0.
- While the queue is non-empty, pop a course and append it to
result. - For each dependent of that course, decrement its in-degree and push it once the in-degree reaches 0.
- Return
resultif it contains allnumCoursescourses; 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]]
- The graph becomes 0 → [1, 2], 1 → [3] and 2 → [3], and the in-degrees are [0, 1, 1, 2].
- Only course 0 has in-degree 0, so the queue starts as [0].
- Pop 0 and add it to the result. Courses 1 and 2 drop to in-degree 0 and are queued.
- Pop 1. Course 3 drops from 2 to 1, which is not zero yet, so nothing is queued.
- 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 []1class Solution {
2 public int[] findOrder(int numCourses, int[][] prerequisites) {
3 List<List<Integer>> graph = new ArrayList<>();
4 int[] indegree = new int[numCourses];
5 for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());
6
7 for (int[] pre : prerequisites) {
8 graph.get(pre[1]).add(pre[0]);
9 indegree[pre[0]]++;
10 }
11
12 Queue<Integer> queue = new LinkedList<>();
13 for (int i = 0; i < numCourses; i++) {
14 if (indegree[i] == 0) queue.offer(i);
15 }
16
17 int[] result = new int[numCourses];
18 int idx = 0;
19 while (!queue.isEmpty()) {
20 int course = queue.poll();
21 result[idx++] = course;
22 for (int next : graph.get(course)) {
23 indegree[next]--;
24 if (indegree[next] == 0) queue.offer(next);
25 }
26 }
27 return idx == numCourses ? result : new int[0];
28 }
29}1class Solution {
2public:
3 vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
4 vector<vector<int>> graph(numCourses);
5 vector<int> indegree(numCourses, 0);
6
7 for (auto& pre : prerequisites) {
8 graph[pre[1]].push_back(pre[0]);
9 indegree[pre[0]]++;
10 }
11
12 queue<int> q;
13 for (int i = 0; i < numCourses; i++) {
14 if (indegree[i] == 0) q.push(i);
15 }
16
17 vector<int> result;
18 while (!q.empty()) {
19 int course = q.front(); q.pop();
20 result.push_back(course);
21 for (int next : graph[course]) {
22 indegree[next]--;
23 if (indegree[next] == 0) q.push(next);
24 }
25 }
26 return result.size() == numCourses ? result : vector<int>();
27 }
28};Time and space complexity
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.
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
resultwhen a cycle exists. The problem wants an empty list, so you must comparelen(result)withnumCourses. - 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.