Course Schedule II

35 min · findOrder()

Knowing that a degree is possible isn't enough; you still need the semester-by-semester plan.

You're given numCourses courses labeled from 0 through numCourses - 1 and a list prerequisites. A pair [course, prerequisite] means prerequisite must appear before course in your answer.

Return a topological order — a list that places every directed dependency before the course that relies on it. If a cycle — a dependency chain that leads back to its starting course — makes such an order impossible, return [].

Every solvable judged input has exactly one valid order. That makes the requested output deterministic: you never need to choose between two equally valid schedules.

Constraints

  • 1 <= numCourses <= 2_000
  • 0 <= prerequisites.length <= 5_000
  • Every pair contains two course labels in the range 0..numCourses - 1.
  • Prerequisite pairs are distinct, and no course is its own prerequisite.
  • Every acyclic input has a unique topological order.

Hints

Start with what is ready

Count each course's incoming prerequisite edges. A course with in-degree zero can safely go next because nothing unfinished blocks it.

Remove completed work

After adding a ready course to the answer, reduce the in-degree of every course that depends on it. A count that reaches zero reveals the next ready course.

Recognize a cycle

If the ready queue becomes empty before your answer contains all courses, the remaining courses depend on one another in a cycle. Return an empty array.

Follow-up

How would you detect whether an arbitrary acyclic graph has one topological order or several? Watch the size of the ready frontier at each step.

Visible cases

Examples

Example 1

ready
Input
numCourses = 2
prerequisites = [
  [
    1,
    0
  ]
]
Expected
[
  0,
  1
]
Why
course 0 unlocks course 1

Example 2

ready
Input
numCourses = 4
prerequisites = [
  [
    1,
    0
  ],
  [
    2,
    1
  ],
  [
    3,
    2
  ],
  [
    2,
    0
  ],
  [
    3,
    1
  ]
]
Expected
[
  0,
  1,
  2,
  3
]
Why
the consecutive dependencies force one order

Example 3

ready
Input
numCourses = 1
prerequisites = []
Expected
[
  0
]
Why
the only course is the whole schedule

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite