Problem 525407 · medium · Phase 05 Advanced Algorithms & Graphs

Course Schedule II

topological sort · directed graphs · kahn's algorithm

The same setup as Course Schedule, but now return the order itself. A topological order lists every node so that all edges point forward; if the graph has a cycle there is no such order.

Given num_courses and prerequisites ([a, b] means take b before a), return any valid order in which to take all the courses. If it is impossible, return an empty list [].

Examples

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

Input:  num_courses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: [0, 1, 2, 3]
Explanation: [0, 2, 1, 3] is also correct

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

Your answer is checked by verifying that it contains every course exactly once and respects every prerequisite, so any valid order passes.

Constraints

  • 1 <= num_courses <= 2000, 0 <= len(prerequisites) <= 5000
  • Target: O(V + E) time

Goals

  • Produce an actual topological ordering, not just a yes/no answer
  • Return a sentinel (empty list) when the graph contains a cycle
  • Handle problems where many different outputs are correct
Starting Python…