Problem 525407 · medium · Level 05 Advanced Algorithms & Graphs

A Valid Order for the Modules

topological sort · directed graphs · kahn's algorithm

A topological order lists every node of a directed graph so that all edges point forward; if the graph has a cycle there is no such order. Here you return the order itself, not just whether one exists.

A degree has num_courses modules numbered 0 .. num_courses - 1, and each pair [a, b] in prerequisites means module b must be passed before module a. Write find_order(num_courses, prerequisites) that returns a study plan: a list holding every module once, in an order that respects all the prerequisites. Any valid plan is accepted. If no plan exists, return the empty list [].

Examples

Input:  num_courses = 3, prerequisites = [[2, 1], [1, 0]]
Output: [0, 1, 2]
Explanation: 0 must come before 1, and 1 before 2, so this is the only order

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

Input:  num_courses = 3, prerequisites = [[1, 0], [2, 1], [1, 2]]
Output: []
Explanation: course 0 can be taken, but courses 1 and 2 each need the other first

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…