103. Course order
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
n = 5, prerequisites = [[2, 0], [2, 1], [4, 2],
[3, 4]][0, 1, 2, 4, 3]Example 2
n = 3, prerequisites = [[0, 1], [1, 2], [2, 0]][]Example 3
n = 3, prerequisites = [][0, 1, 2]Constraints
nis a whole number from 0 to 100.prerequisiteshas 0 to 300 pairs[a, b]of course numbers from 0 ton - 1. A pair can appear more than once.
Submit also runs 10 more tests you can't see.
- Count each course's requirements not yet met, and list for each course the courses waiting on it. A course with nothing unmet can be taken now.
- Keep the courses that can be taken in a heap (
heapq), soheappopalways gives the smallest. Taking a course meets one requirement of every course waiting on it; any that reach 0 go into the heap. - If the heap empties before all
ncourses are taken, the rest wait on each other in a loop: return[]. A plain queue (first in, first out) can give a different order than smallest-first.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.