Course Schedule II – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the graph problem
- Every course is a vertex and every prerequisite pair is a directed edge.
- We need a topological ordering: every prerequisite must appear before the course that depends on it.
Step 2: Brute-force by repeatedly scanning prerequisites
- In each round, search for courses whose prerequisites are already taken.
- This is correct but can revisit the full prerequisite list many times, giving roughly
O(V * E)work.
Step 3: Use indegrees to avoid repeated rescans
- Precompute each course's indegree and adjacency list once.
- Then each edge is processed exactly once when its prerequisite is removed from the queue.
Step 4: Run Kahn's algorithm with a FIFO queue
- Seed the queue with every course whose indegree is zero.
- Pop courses, append them to the answer, and decrement the indegree of their outgoing neighbors.
Step 5: Dry run / queue trace
Trace
numCourses = 4,prerequisites = [[1,0],[2,0],[3,1],[1,2]].step queue before pop popped indegree updates order start [0]- indegrees = [0,2,1,1][]1 [0]01 -> 1,2 -> 0, enqueue2[0]2 [0,2]21 -> 0, enqueue1[0,2]3 [0,2,1]13 -> 0, enqueue3[0,2,1]4 [0,2,1,3]3none [0,2,1,3]Every course appears exactly once, so the graph is acyclic and the built order is valid.
Step 6: Final solution and complexity
Kahn's algorithm processes each course and prerequisite edge once, giving
O(V + E)time withO(V + E)graph storage.