AlgoFrames

Course schedule II

Standard · Write code · about 12 min

There are numCourses courses numbered 0 to numCourses − 1. Each pair [a, b] in prerequisites means course b must be taken before course a. Return an order that takes every course after its prerequisites. Any valid order is accepted. Return [] if no order exists.

Example 1

Input:

[4,[[1,0],[2,0],[3,1],[3,2]]]

Output:

[0,1,2,3]

[0, 2, 1, 3] is also accepted. Labels show in-degrees.

Example 2

Input:

[2,[[1,0],[0,1]]]

Output:

[]

Each course needs the other first.

Constraints

  • 1 ≤ numCourses ≤ 500
  • 0 ≤ prerequisites.length ≤ 2000
  • 0 ≤ a, b < numCourses

Learn the idea first: Topological sort: Kahn's algorithm and DFS finishing order, a visual lesson.

More Topological sort: Kahn's algorithm and DFS finishing order problems