150 XP

103. Course order

Expert graphs sorting

A school has n courses, numbered 0 to n - 1. Some courses require others first: the pair [a, b] means course a can only be taken after course b.

Write a function course_order(n, prerequisites) that returns an order in which to take all n courses, as a list of their numbers, so that every course comes after all the courses it requires:

  • Many orders can work. Return this one: whenever several courses could be taken next, take the one with the smallest number.
  • If no order works, because some courses require each other in a loop (a course that requires itself included), return [].
  • With no courses, the order is [].

Example 1

Inputn = 5, prerequisites = [[2, 0], [2, 1], [4, 2], [3, 4]]
Output[0, 1, 2, 4, 3]
Explanation2 waits for 0 and 1; then 4, then 3.

Example 2

Inputn = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]
Output[]
Explanation0 needs 1, 1 needs 2, 2 needs 0: a loop.

Example 3

Inputn = 3, prerequisites = []
Output[0, 1, 2]
ExplanationNothing required: smallest first.

Constraints

  • n is a whole number from 0 to 100.
  • prerequisites has 0 to 300 pairs [a, b] of course numbers from 0 to n - 1. A pair can appear more than once.

Submit also runs 10 more tests you can't see.

Code
def course_order(n, prerequisites):
    """Order the courses so requirements come first.

    n: int, how many courses, numbered 0 to n - 1
    prerequisites: list of [a, b] pairs: a needs b first
    Returns: list of int, every course in a working order
        (smallest first when free to choose), or [] if none
    """
    # Write your code here
    pass