Course Schedule II
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #210
There are numCourses courses. prerequisites[i] = [a, b] means you must take b before a. Return any valid order in which to take all courses, or [] if that's impossible (there's a cycle). The tests list every valid order.
Examples
text
numCourses = 2, prerequisites = [[1,0]] → [0,1]
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] → [0,1,2,3] or [0,2,1,3]
numCourses = 2, prerequisites = [[1,0],[0,1]] → []Hints
- This is a topological sort of the graph with edges
b → a. - Courses with no remaining prerequisites can be taken now. Taking one may free up others.
Approach
Kahn's algorithm (BFS topological sort):
- Build an adjacency list
b → aand anindeg[a]count. - Queue every course with
indeg == 0. - Pop
u, append it toorder, and decrementindegof each successor. When one hits 0, enqueue it. - If
len(order) < numCourses, some courses never reached in-degree 0. They lie on a cycle, so return[].
DFS alternative: three-color DFS (white/gray/black). Output a node in post-order, then reverse the list. Reaching a gray node means a cycle.
Complexity
Time: O(V + E). Space: O(V + E).
Python solution
from collections import deque
def findOrder(numCourses, prerequisites):
adj = [[] for _ in range(numCourses)]
indeg = [0] * numCourses
for a, b in prerequisites:
adj[b].append(a)
indeg[a] += 1
q = deque(i for i in range(numCourses) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == numCourses else []JavaScript solution
function findOrder(numCourses, prerequisites) {
const adj = Array.from({ length: numCourses }, () => []), indeg = new Array(numCourses).fill(0);
for (const [a, b] of prerequisites) { adj[b].push(a); indeg[a]++; }
const q = [];
for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
for (let h = 0; h < q.length; h++) for (const v of adj[q[h]]) if (--indeg[v] === 0) q.push(v);
return q.length === numCourses ? q : [];
}