Schedule Courses Under Prerequisite Rules
Trees & GraphsAuto-graded · 23 test casesLast updated
Produce a deterministic course order that respects prerequisite pairs using a queue-based topological sort, or an empty list if the prerequisites contain a cycle.
A school offers num_courses courses, labeled 0 to num_courses - 1. Some courses have prerequisites, given as a list of pairs prereq_pairs. A pair [a, b] means course b must be finished before course a can be taken.
Return a full ordering of all courses in which every course appears after all of its prerequisites. If the prerequisites contain a cycle, so that no such ordering exists, return an empty list.
Required procedure
Many valid orderings can exist, so the output must be exactly the one produced by the following queue-based procedure:
- For each pair
[a, b]in input order, record that finishingbunlocksa, and count one more unmet prerequisite fora. A repeated pair counts again each time it appears. - Put every course with zero unmet prerequisites into a FIFO queue, in increasing label order.
- Repeat while the queue is not empty:
- Remove the front course and append it to the result.
- Go through the courses it unlocks in the order their pairs appeared in the input. For each one, reduce its unmet count by one. If the count becomes zero, add that course to the back of the queue.
- If the result contains all
num_coursescourses, return it. Otherwise return[].
The answer is all-or-nothing: if any course is stuck on or behind a cycle, return [] rather than a partial order. A pair like [a, a] is a cycle. If num_courses is 0, return [].
Constraints
0 <= num_courses <= 10^50 <= len(prereq_pairs) <= 2 * 10^5- Each pair has exactly two integers, each in
[0, num_courses - 1]. - Pairs may repeat, and the graph may be disconnected.
- The solution should run in time roughly linear in
num_courses + len(prereq_pairs).
Examples
Example 1
Input: plan_course_order(2, [[1, 0]])
Output: [0, 1]
Example 2
Input: plan_course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 3
Input: plan_course_order(2, [[1, 0], [0, 1]])
Output: []
Hints
Hint 1
Treat each pair [a, b] as a directed edge from b to a. A valid schedule is a topological ordering of this graph.
Hint 2
Track how many prerequisites each course still lacks. Courses with zero are ready to take now, and finishing a course lowers the counts of the courses it unlocks.
Hint 3
Use a deque for the ready courses. If fewer than num_courses courses ever become ready, a cycle blocked the rest, so return an empty list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the courses as a directed graph. Each pair [a, b] becomes an edge b -> a. A valid schedule is a topological ordering, which exists exactly when the graph has no directed cycle.
We use a queue-based topological sort (Kahn's algorithm):
- Build, for each course, the list of courses it unlocks (in input order), and count each course's unmet prerequisites.
- Queue every course with no unmet prerequisites, in increasing label order.
- Repeatedly take the front course and append it to the result. Then decrease the unmet count of each course it unlocks, and enqueue any course whose count reaches zero.
- If the result holds all courses, return it. Otherwise return
[].
The fixed queue discipline and input-order adjacency make the output deterministic.
Why it is correct
- The order is valid. A course is appended only after its count reaches zero. That happens only after every prerequisite has already been appended. Duplicate pairs add to the count and to the adjacency list equally, so they cancel out.
- Cycle detection is exact. No course on a cycle can ever reach a count of zero, because it waits on another cycle member that is also never emitted. So the result is shorter than
num_courses. In an acyclic graph there is always at least one course with no unmet prerequisites. Removing it leaves a smaller acyclic graph, so by induction every course is emitted. - Self-pairs
[a, a]makeawait on itself, so they are treated as cycles.
Complexity
- Time:
O(n + E), whereE = len(prereq_pairs). Each course is enqueued and dequeued once, and each pair is processed once. - Space:
O(n + E)for the adjacency lists, counts, queue, and output.
The approach is iterative, so long dependency chains do not hit Python's recursion limit.
Reference solution
from collections import deque
from typing import List
def plan_course_order(num_courses: int, prereq_pairs: List[List[int]]) -> List[int]:
unlocks = [[] for _ in range(num_courses)]
unmet = [0] * num_courses
for course, prereq in prereq_pairs:
unlocks[prereq].append(course)
unmet[course] += 1
ready = deque(i for i in range(num_courses) if unmet[i] == 0)
order = []
while ready:
cur = ready.popleft()
order.append(cur)
for nxt in unlocks[cur]:
unmet[nxt] -= 1
if unmet[nxt] == 0:
ready.append(nxt)
return order if len(order) == num_courses else []