Course Schedule II

Graphs, problem 5 of 8

Course Schedule II

Medium

LC #210

topological sortbfscycle detection

Not attempted yet

There are num_courses courses labelled 0..num_courses-1. Each pair [a, b] in prerequisites means you must take course b before course a.

Return an order in which you can take all the courses. If several orders work, return any of them. If it's impossible (the prerequisites contain a cycle), return [].

Example 1

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

Example 2

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

[0,2,1,3] is also accepted.

Example 3

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

Each course waits for the other.

Constraints

  • 1 <= num_courses <= 2 * 10^4
  • 0 <= len(prerequisites) <= 4 * 10^4
  • all pairs are distinct

Python

Loading draft…

Test results

9 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 6 hidden

Run examples, then submit all tests.