Plan the Course Order

Implement orderCourses

A school offers n courses, and some courses can only be taken after others. The requirements are given as an adjacency list of a directed graph: courses[u] holds the courses that require course u first. Produce a plan that takes every course after its requirements, or report that this is impossible.

When several plans are valid, return the lexicographically smallest, and return an empty list when the requirements contain a cycle.

Example 1:

Input: courses = [[],[0],[0],[1,2],[3]]

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

Example 2:

Input: courses = [[1],[0]]

Output: []

Example 3:

Input: courses = [[],[]]

Output: [0,1]

+ 15 hidden test cases run on Submit.

Constraints:

  • ●1 ≤ n ≤ 8 courses numbered 0 … n-1; courses[u] lists, in increasing order, every course v that requires course u to be completed first (adjacency-list form of a directed graph)
  • ●A course may require itself (a road u → u), which can never be satisfied; the graph may contain cycles
  • ●A valid plan takes every course exactly once, each one after all the courses it requires
  • ●Return the lexicographically smallest valid plan, or an empty list if no valid plan exists

courses =

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