AAI Agentic Handbook
Problem 42 · Graphs

Course Schedule II (Topological Sort)

MediumClassic DSA & systems
01Problem

Given numCourses and prerequisite pairs [course, prereq], return any valid order to take all courses, or an empty list if a cycle makes it impossible.

02Key insight

Kahn's algorithm: repeatedly take nodes with in-degree zero. If fewer than n nodes are emitted, the remainder form at least one cycle.

03Solution

Try it first.

TimeO(V+E)
SpaceO(V+E)
tests.py · 4 passing
tests.pypython5 lines
assert find_order(2, [[1, 0]]) == [0, 1]
assert find_order(2, [[1, 0], [0, 1]]) == []
o = find_order(4, [[1,0],[2,0],[3,1],[3,2]])
assert o[0] == 0 and o[-1] == 3 and len(o) == 4
assert find_order(1, []) == [0]
04Staff-level follow-up

How would you schedule a DAG of jobs in parallel (e.g. Spark stages)? Process Kahn's queue level by level; each level's jobs run concurrently and the level count is the critical-path length.