Practice · Topological sort · 2 of 2

Course Order

There are numCourses courses, numbered from 0. Each pair [a, b] in prerequisites means course b must be taken before course a.

Return an order in which to take every course once, with each course after all of its prerequisites. If several orders work, return any of them. If the prerequisites go round in a loop, so no order works, return an empty list.

Example 1

Input
numCourses = 3, prerequisites = [[1, 0], [2, 1]]
Output
[0, 1, 2]
Course 0 unlocks 1, which unlocks 2.

Example 2

Input
numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output
[0, 1, 2, 3]
[0, 2, 1, 3] is right too.

Example 3

Input
numCourses = 2, prerequisites = [[0, 1], [1, 0]]
Output
[]
Each course waits for the other.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • prerequisites holds at most 5000 pairs, each of two different courses, with no pair repeated.