KatInterview

Minimum Batches to Complete All Courses with Prerequisites

Trees & GraphsAuto-graded · 16 test cases
HardAuto-gradedTrees & Graphsgraphstopological-sortBFS

Last 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 course a must be completed before course b can 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 prerequisites is empty, all courses belong to batch 0.
  • There are no duplicate prerequisite pairs, but a course may have multiple prerequisites.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ 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 [].