Semester Planner: Build a Valid Course Sequence
Trees & GraphsAuto-graded · 21 test casesLast updated
Produce a deterministic topological ordering of courses from prerequisite pairs, or an empty list when a circular requirement makes it impossible.
Semester Planner
A school offers course_count courses, numbered 0 through course_count - 1. You receive a list prereq_pairs, where each entry [a, b] means course b must be completed before course a can be taken.
Return a sequence containing every course exactly once, such that each course appears after all of its prerequisites. If the requirements contain a circular dependency, so that no such sequence exists, return an empty list.
Required output order
Several valid sequences may exist, but your function must return the one built by the following procedure, so that results are exactly reproducible:
- For every course, count how many entries in
prereq_pairsname it as the first elementa. Duplicate entries each count separately. - Start a first-in-first-out queue holding every course whose count is
0, in increasing numeric order. - Repeat while the queue is not empty:
- Remove the course at the front and append it to the result.
- Go through
prereq_pairsin its given order. For each entry[a, b]wherebis the course just removed, reduce the count ofaby one. If that count becomes0, addato the back of the queue.
- If the result contains all
course_countcourses, return it. Otherwise return[].
A course that lists itself as its own prerequisite can never be taken, so the answer in that case is [].
Constraints
1 <= course_count <= 20000 <= len(prereq_pairs) <= 5000- Each entry of
prereq_pairshas exactly two integers in the range[0, course_count - 1]. - The same pair may appear more than once, and the requirement graph may be split into several disconnected parts.
- Return
[]if and only if the requirements contain a cycle (including a self-requirement).
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 b -> a, and track for every course how many prerequisites are still unmet.
Hint 2
Courses with zero unmet prerequisites can be taken right now. Take one, then lower the counter of every course that was waiting on it.
Hint 3
If you finish with fewer courses than course_count, the leftover ones are stuck behind a cycle, so return an empty list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each pair [a, b] as a directed edge b -> a: finishing b brings a closer to being available. A valid course sequence is a topological ordering of this graph, and one exists exactly when the graph has no cycle.
We use Kahn's algorithm:
- Build an adjacency list
unlocks[b]holding the courses that depend onb, in the order the pairs appear. Also buildmissing[a], the number of unmet prerequisites ofa. - Put every course with
missing == 0into a FIFO queue, in increasing label order. - Pop the front course and append it to the result. Then walk its
unlockslist, decrementingmissingfor each dependent. When a dependent reaches0, push it to the queue. - If the result holds all courses, return it. Otherwise return
[].
The adjacency lists preserve pair order and the queue is FIFO, so the output matches the order defined in the statement exactly.
Why it is correct
- Valid order: a course enters the queue only after its counter reaches zero, meaning all its prerequisites were already appended to the result.
- Acyclic graphs finish: every non-empty DAG has a node with no incoming edges. Removing it leaves a smaller DAG, so by induction the queue never runs dry before every course is emitted.
- Cycles are detected: consider the first course on a cycle that would be popped. Its cycle predecessor would have had to be popped earlier to zero its counter, a contradiction. So cycle courses are never emitted and the result is shorter than
course_count. - Self-loops and duplicates: a self-pair
[a, a]keepsmissing[a] >= 1forever, giving[]. Duplicate pairs raise the counter and are decremented the same number of times, so they stay consistent. - Disconnected parts: seeding the queue with all zero-count courses handles every component.
Complexity
With V = course_count and E = len(prereq_pairs):
- Time: O(V + E), since each course is queued once and each edge is processed once.
- Space: O(V + E) for the adjacency lists, counters, queue, and result.
Reference solution
from collections import deque
from typing import List
def plan_course_order(course_count: int, prereq_pairs: List[List[int]]) -> List[int]:
unlocks = [[] for _ in range(course_count)]
missing = [0] * course_count
for course, prereq in prereq_pairs:
unlocks[prereq].append(course)
missing[course] += 1
queue = deque(c for c in range(course_count) if missing[c] == 0)
order = []
while queue:
current = queue.popleft()
order.append(current)
for nxt in unlocks[current]:
missing[nxt] -= 1
if missing[nxt] == 0:
queue.append(nxt)
return order if len(order) == course_count else []