Skills101
← All coding problems

Course Schedule II (Topological Sort)

mediumGraphs+20 XPTime limit 2s

Same setup as Course Schedule: n courses, and a pair a b means course b must be finished before course a. Print an order in which you can take all courses — or -1 if it is impossible.

Many orders can be valid, so print the specific one where, at every step, you take the smallest-numbered course that is currently available (all its prerequisites done). This is the lexicographically smallest valid order.

Input:

  • line 1: n m
  • next m lines: a pair a b

Output: the n course numbers in order on one line, or -1.

Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ m ≤ 10⁵, a ≠ b.

Think about it: Kahn's algorithm with a min-heap (priority queue) instead of a plain queue picks the smallest available course each time: O((n + m) log n).

Sample input 1

2 1
1 0

Sample output 1

0 1

Sample input 2

4 4
1 0
2 0
3 1
3 2

Sample output 2

0 1 2 3

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.