Course Schedule
There are n courses, and a list of pairs [a, b] meaning course b must be completed before course a. Determine whether it is possible to finish all courses.
- 1 ≤ n ≤ 2000
- 0 ≤ prerequisites.length ≤ 5000
- All pairs distinct
- Prerequisites = directed edges
- Feasible iff the dependency graph has no cycle
- Peel off nodes with in-degree zero
Constraints of the form "A before B" are edges in a directed graph; a valid schedule exists exactly when the graph has no cycle, and any topological order is a valid schedule. Kahn's algorithm (peel off zero in-degree nodes) also detects impossibility: if it stops before emitting every node, a cycle remains.
Build a directed graph from prerequisite to course and compute in-degrees. Run Kahn's algorithm: enqueue all courses with in-degree 0, repeatedly dequeue one, count it as taken and decrement the in-degree of each dependent, enqueuing those that reach 0. If the number of dequeued courses equals n the graph is a DAG and all courses can be finished; otherwise the leftovers form a cycle.
- DFS with three colours (unvisited/in-progress/done) detects a cycle when a grey node is revisited and also yields an order in reverse post-order.