Course Schedule II

medium

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.

Hints

Build the prerequisite graph (edge b -> a) and topologically sort it.
Use Kahn's algorithm; emit the smallest ready course from a min-heap for the smallest order.
If fewer than numCourses get emitted, a cycle exists — return [].

Common doubts

A plain queue gives some valid order; the min-heap always emits the smallest ready course, producing the lexicographically smallest schedule.
If Kahn's outputs fewer than numCourses courses, the leftovers are in a cycle — return an empty array.
Yes — empty means impossible; a single-element order means that one course has no prerequisites.

Interview follow-ups

Reverse of DFS finish times gives a topological order, though not the lexicographically smallest without extra care.
That's exponential in general; you'd enumerate via backtracking over ready sets.

Fun facts

  • LeetCode 210 — Course Schedule I with the actual schedule returned.
  • This is exactly how build tools compute a compilation order.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
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.
Example 2
Input: numCourses = 2, prerequisites = [[0,1],[1,0]]
Output: []
A cycle makes any order impossible.
Constraints

- 1 <= numCourses <= 10^5 - 0 <= prerequisites.length <= 10^5 - no duplicate prerequisite pairs

Solve this problem →