You must take numCourses courses (0 .. numCourses-1). prerequisites[i] = [a, b] means course b must be taken before course a. Return a valid order in which to take all courses; if several are valid, return the lexicographically smallest. If finishing all courses is impossible (a cycle), return an empty array.
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0, 1, 2, 3] 0 first; then 1 before 2; then 3.
Input: numCourses = 2, prerequisites = [[0,1],[1,0]] Output: [] A cycle makes any order impossible.
- 1 <= numCourses <= 10^5 - 0 <= prerequisites.length <= 10^5 - no duplicate prerequisite pairs
This is Course Schedule I plus the actual order. Build the prerequisite graph ([a, b] ⇒ edge b → a) and run Kahn's algorithm, outputting courses as their in-degree reaches 0. If a cycle blocks some courses (fewer than numCourses get output), return [].
Several courses may be ready at once, so for the lexicographically smallest order always emit the smallest-labelled ready course — a min-heap. The brute version rescans for the smallest ready course each step (O(V²)); the heap version is O((V+E) log V).
“Which order if several are valid?”
Lexicographically smallest.
“What if it's impossible?”
Return an empty array.
I run Kahn's on the prerequisite graph, emitting the smallest ready course from a min-heap.
If fewer than numCourses come out, a cycle exists — return empty.
Worked example — numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
ready {0} -> 0; ready {1,2} -> 1 then 2; ready {3} -> 3
order = [0, 1, 2, 3]
Of the prerequisite DAG.
Emit the smallest ready course each step.
A cycle prevents ordering all courses.
| Smallest-zero scan | Kahn's + min-heap | |
|---|---|---|
| Pick next | scan all courses | pop the heap |
| Time | O(V²) | O((V+E) log V) |
| Cycle | return [] | return [] |
Both produce the same lexicographically-smallest order (or empty). Full code is in the Approaches selector below.
Key takeaway
Kahn's on the prerequisite graph, emitting the smallest ready course (min-heap) — the lexicographically smallest order. Empty if a cycle blocks completion. O((V+E) log V).
heap of indeg-0 courses; pop smallest, output, decrement successors if output count < numCourses -> []