Course Schedule Order
You need to take num_courses courses, labeled 0 to num_courses - 1. Each pair prerequisites[i] = [a, b] means you must take course b before course a.
Return an order in which you can take every course. If several orders work, return any of them. If no order works, return an empty array.
The tests accept any valid order. For each test they check your array and report num_courses if it's a valid order, 0 if it's empty and -1 if it breaks a prerequisite or isn't a list of every course exactly once.
Example 1
Input: num_courses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] Output: [0, 1, 2, 3]
Course 0 comes first, courses 1 and 2 both need only 0, and course 3 needs both. [0, 2, 1, 3] is also correct.
Example 2
Input: num_courses = 2, prerequisites = [[1, 0], [0, 1]] Output: []
Each course requires the other, so neither can be taken first.
Constraints
1 <= num_courses <= 20000 <= prerequisites.length <= num_courses * (num_courses - 1)prerequisites[i].length == 20 <= a, b < num_coursesanda != b- All pairs are distinct.
Approach
Draw an edge from b to a for every pair [a, b]. A valid order lists every course after all of the courses that point to it. That's a topological order, and it exists exactly when the graph has no cycle.
Kahn's algorithm builds one directly. Count each course's prerequisites, called its in-degree. Every course with an in-degree of 0 can be taken immediately, so put those in a queue. Take a course from the queue, add it to the order and decrease the count of each course it unlocks. Any course whose count drops to 0 joins the queue.
If the order ends up holding every course, it's valid. If some courses never reach a count of 0, they're waiting on each other in a cycle, so return an empty array.
Steps
- Build a list of the courses each course unlocks and a count of prerequisites for each course.
- Put every course with a count of
0in a queue. - While the queue isn't empty, take a course, append it to the order and decrease the count of each course it unlocks, queuing any that reach
0. - Return the order if it holds every course. Otherwise return an empty array.
from collections import deque
from typing import List
def find_order(num_courses: int, prerequisites: List[List[int]]) -> List[int]:
unlocks = [[] for _ in range(num_courses)] # unlocks[b] = courses that need b first
waiting = [0] * num_courses # number of prerequisites each course still waits on
for course, before in prerequisites:
unlocks[before].append(course)
waiting[course] += 1
ready = deque(c for c in range(num_courses) if waiting[c] == 0)
order = []
while ready:
course = ready.popleft()
order.append(course)
for nxt in unlocks[course]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
ready.append(nxt)
# If some course never became ready, the prerequisites contain a cycle.
return order if len(order) == num_courses else []Complexity
- Time:
O(V + E), whereVis the number of courses andEthe number of prerequisites. Each course is queued once and each edge is followed once. - Space:
O(V + E)for the adjacency lists, counts and queue.
Common mistakes
- Reversing the edge.
[a, b]meansbcomes beforea, so the edge goes frombtoa. - Returning a partial order when there's a cycle instead of an empty array.
- Forgetting courses with no prerequisites at all. They belong in the order too.