Skip to main content

Course Schedule Order

MediumPremium

You need to take num_courses courses, labeled 0 to num_courses - 1. Each pair prerequisites[i] = [a, b] means you must take course b before course a.

Return an order in which you can take every course. If several orders work, return any of them. If no order works, return an empty array.

The tests accept any valid order. For each test they check your array and report num_courses if it's a valid order, 0 if it's empty and -1 if it breaks a prerequisite or isn't a list of every course exactly once.

Example 1

Input: num_courses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] Output: [0, 1, 2, 3]

Course 0 comes first, courses 1 and 2 both need only 0, and course 3 needs both. [0, 2, 1, 3] is also correct.

Example 2

Input: num_courses = 2, prerequisites = [[1, 0], [0, 1]] Output: []

Each course requires the other, so neither can be taken first.

Constraints

  • 1 <= num_courses <= 2000
  • 0 <= prerequisites.length <= num_courses * (num_courses - 1)
  • prerequisites[i].length == 2
  • 0 <= a, b < num_courses and a != b
  • All pairs are distinct.