iq.lab
Python starts when a code cell comes near or you run one
mediumTopological sort target 25 min

Find an order for the courses

A school offers num_courses courses, numbered 0 to num_courses - 1. Each pair [a, b] in prerequisites means course b must be finished before course a can start. In every pair, a and b are different courses, and no pair appears twice.

Return a list that holds every course exactly once, in an order you could take them one at a time: each course comes after all of its prerequisites. If several orders work, return any of them; the tests accept every valid order. If no order works, return an empty list [].

Example 1
Inputnum_courses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]Output[0, 1, 2, 3]

1 and 2 need only 0, and 3 needs both of them. [0, 2, 1, 3] is also accepted.

Example 2
Inputnum_courses = 3, prerequisites = [[0, 2]]Output[1, 2, 0]

Only 2 before 0 is required, and 1 needs nothing. Any order with 2 before 0 is accepted, such as [2, 0, 1].

Example 3
Inputnum_courses = 2, prerequisites = [[0, 1], [1, 0]]Output[]

Each course waits for the other, so no order exists.

Constraints
  • 1 ≤ num_courses ≤ 2 × 104

  • 0 ≤ len(prerequisites) ≤ 2 × 104

  • 0 ≤ a, b < num_courses and a ≠ b

  • No pair appears twice.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.