Minimum Batches to Complete All Courses with Prerequisites
Trees & GraphsAuto-graded · 16 test casesLast updated
Tests topological ordering (Kahn's algorithm / BFS layering) to schedule dependent courses into the fewest sequential batches where each batch runs in parallel.
Course Batch Scheduler
A university offers n courses numbered 0 through n - 1. Some courses have prerequisites: before enrolling in course b, you must have already completed (in a previous batch) course a.
Courses are offered in discrete batches. Within a single batch, any number of courses may run simultaneously. A course can only be enrolled in a batch if all of its prerequisites were completed in strictly earlier batches.
You are given:
n— the total number of courses.prerequisites— a list of pairs[a, b]meaning courseamust be completed before coursebcan start.
Return a list of batches, where each batch is a sorted list of course numbers that should be taken in that batch, ordered from the earliest batch to the latest.
If the prerequisite graph contains a cycle (making it impossible to complete all courses), return an empty list [].
Notes
- Every course must appear in exactly one batch.
- Produce the minimum number of batches possible (i.e., assign each course to the earliest batch it can legally start).
- Courses within a batch must be listed in ascending order.
- Batches must be listed in chronological order (batch 0 first, then batch 1, etc.).
- If
prerequisitesis empty, all courses belong to batch 0. - There are no duplicate prerequisite pairs, but a course may have multiple prerequisites.
Constraints
1 ≤ n ≤ 20000 ≤ len(prerequisites) ≤ min(n*(n-1), 10000)- Each pair
[a, b]contains distinct values in[0, n-1] - No duplicate pairs in
prerequisites
Examples
Example 1
Input: schedule_course_batches(4, [[0, 1], [0, 2], [1, 3], [2, 3]])
Output: [[0], [1, 2], [3]]
Example 2
Input: schedule_course_batches(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Example 3
Input: schedule_course_batches(5, [])
Output: [[0, 1, 2, 3, 4]]
Hints
Hint 1
Compute the in-degree of every node. Courses with in-degree 0 form batch 0 — they have no prerequisites.
Hint 2
Use BFS (Kahn's algorithm) level by level: after processing one batch, decrement the in-degree of each neighbour; nodes whose in-degree drops to 0 join the next batch.
Hint 3
If the total number of courses assigned across all batches is less than n after BFS completes, a cycle exists — return [].
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a direct application of topological sort with BFS level layering (Kahn's algorithm).
Key Insight
The "minimum number of batches" constraint is equivalent to assigning each course to the earliest possible layer in the topological order. In Kahn's algorithm, processing the BFS queue level-by-level (draining all current zero-in-degree nodes before moving on) naturally produces exactly these layers.
Algorithm
-
Build the graph: For each prerequisite pair
[a, b], add a directed edgea → bin the adjacency list and incrementin_degree[b]. -
Seed batch 0: Every course with
in_degree == 0(no prerequisites) starts in the initial queue. -
BFS layer-by-layer:
- Snapshot the current queue size — all courses currently in the queue form one batch.
- Dequeue each of them, append to the current batch, and for every neighbor decrement its in-degree. If a neighbor's in-degree hits 0, enqueue it (it will belong to the next batch).
- Sort the current batch and append to results.
-
Cycle detection: Count every course scheduled. If
total_scheduled < nafter BFS terminates, at least one cycle prevented some courses from ever reaching in-degree 0 → return[].
Correctness
- A course can only enter the queue once all its prerequisites are complete, so the ordering is valid.
- Draining the entire current-level queue before advancing ensures no course is delayed to a later batch unnecessarily, giving the minimum batch count.
- Sorting within each batch provides the unique deterministic output required.
Complexity
- Time: O(n + E) for building the graph and BFS, plus O(n log n) for the per-batch sorts (total sort work is bounded by O(n log n) overall). Dominant: O(n + E).
- Space: O(n + E) for the adjacency list and in-degree array.
from typing import List
from collections import deque
def schedule_course_batches(n: int, prerequisites: List[List[int]]) -> List[List[int]]:
adj = [[] for _ in range(n)]
in_degree = [0] * n
for a, b in prerequisites:
adj[a].append(b)
in_degree[b] += 1
queue = deque()
for course in range(n):
if in_degree[course] == 0:
queue.append(course)
batches = []
total_scheduled = 0
while queue:
batch_size = len(queue)
current_batch = []
for _ in range(batch_size):
course = queue.popleft()
current_batch.append(course)
total_scheduled += 1
for neighbor in adj[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
batches.append(sorted(current_batch))
if total_scheduled != n:
return []
return batches