Course scheduling
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Course scheduling asks whether all courses can be completed given their prerequisites, and in what order or how many terms. It is the classic example of ordering with rules, and the same logic drives any plan with "do this first" constraints.
Practical use cases
- Web app: Degree planner in a college portal. A student picks 8 subjects and the portal checks prerequisites. It reports "possible in 3 semesters" and lists each term, or warns "Subjects X and Y need each other, please contact the office". It can also show which courses can be taken together in the same term, which helps students balance their workload with less guessing.
- Web app: Project plan in a task tool. A team lead drags tasks and sets "starts after" links. The tool computes an order and the earliest finish round, and shows a red banner if the links form a loop.
- Web app: CI pipeline stages. A deployment pipeline has steps: test, build, migrate, deploy. The platform arranges them in rounds so that steps with no waiting run together, and rejects a config where two steps wait on each other.
- System: Dependency installers. Package managers verify that the full set of requirements can be satisfied before downloading anything, so that you never end up with a half install that can never finish. That saves time and bandwidth for everyone.
The story: Mira Plans Her Semesters
Mira's older cousin Aarav was choosing subjects for college, and he was panicking. "To take Machine Learning I need Python and Maths. For Python I need Basics. The Project needs ML. How do I know if I can even finish, and how many semesters will it take?"
Mira grabbed a sheet and wrote each course as a bubble. For every rule she drew an arrow from the prerequisite to the course that needs it. "Look, it is the same as our morning-routine map. Courses are tasks and prerequisites are the 'must be done first' arrows."
"Each semester," she said, "take everything that has no unfinished prerequisite. When the semester ends, those courses are done, and some new ones unlock. Keep going." After four rounds the whole sheet was done. Then Aarav showed a scary syllabus where Course X needed Y, and Y needed X. Semester 1 came out empty: nobody could start.
This is the famous interview problem Course Schedule: given courses and prerequisite pairs, can all courses be finished, and in what order? It is topological sorting wearing a college uniform. If you finish with fewer courses than you started with, there is a cycle in the prerequisites.
How to spot this problem, and where you need it
You have items with prerequisites and must tell a user whether everything can be completed, and if so, in which order or in how many rounds.
Signs you need it
- The wording is "can you finish all tasks", "is it possible", or "minimum number of semesters or rounds".
- Items list their prerequisites by id, for example course 5 needs 2 and 3.
- Users can enter their own dependencies, so loops are a real risk.
Where to use it in a project
- Planner screens in education portals, project tools or workflow builders that validate user-entered dependencies.
- Pipeline and installer configs checked before anything actually runs.
The solution
Build the graph with an arrow from each prerequisite to its course. Count how many prerequisites each course still has. Each round, take all courses with zero remaining; that round is one semester. Remove them, reduce counts of the courses depending on them, and repeat. If every course gets taken, the plan is possible and the number of rounds is the term count. If some remain, they sit in a loop and the plan is impossible.
Payoff: Before: students discover a prerequisite clash in the last semester. After: the portal says "impossible, X and Y need each other" while they are choosing.
Explain it like I am 8
Think of levels in a video game. You can only play level 3 after finishing level 2. Each day you play every level that is unlocked. If some levels each wait on one another, they will never unlock, and the game cannot be completed.
How it works, step by step
- Make a node for each course. For every pair "
course needs pre", draw an arrowpre → course. - Count how many prerequisites each course still has (its in-degree).
- This semester: take all courses with zero prerequisites left. They form one "layer".
- After the semester, reduce the prerequisite count of every course that depended on them. Courses that hit zero are next semester's layer.
- When no course is left to take: if you took all of them, answer yes (the number of layers is the minimum semesters). Otherwise there is a cycle and the answer is no.
The code in four languages
PHP
<?php
// Course Schedule: returns the semesters (each a list of courses), or null if impossible.
// $prereqs holds pairs [course, prerequisite], like [1, 0] = "course 1 needs course 0".
function plan(int $n, array $prereqs): ?array {
$unlocks = array_fill(0, $n, []); // pre => courses that depend on it
$left = array_fill(0, $n, 0); // prerequisites still unfinished
foreach ($prereqs as [$course, $pre]) {
$unlocks[$pre][] = $course;
$left[$course]++;
}
$ready = [];
for ($i = 0; $i < $n; $i++) {
if ($left[$i] === 0) $ready[] = $i;
}
$semesters = [];
$taken = 0;
while ($ready) {
$semesters[] = $ready; // take everything that is open
$taken += count($ready);
$next = [];
foreach ($ready as $u) {
foreach ($unlocks[$u] as $v) {
$left[$v]--;
if ($left[$v] === 0) $next[] = $v; // just unlocked
}
}
$ready = $next;
}
return $taken === $n ? $semesters : null;
}
$result = plan(5, [[2, 0], [3, 1], [3, 2], [4, 3]]);
foreach ($result as $i => $courses) {
echo 'Semester ' . ($i + 1) . ': ' . implode(', ', $courses) . PHP_EOL;
}
echo plan(2, [[0, 1], [1, 0]]) === null ? 'Impossible: prerequisites loop' : 'ok';
echo PHP_EOL;JavaScript
// Course Schedule: returns the semesters (each a list of courses), or null if impossible.
// prereqs holds pairs [course, prerequisite], like [1, 0] = "course 1 needs course 0".
function plan(n, prereqs) {
const unlocks = Array.from({ length: n }, () => []); // pre => courses that depend on it
const left = new Array(n).fill(0); // prerequisites still unfinished
for (const [course, pre] of prereqs) {
unlocks[pre].push(course);
left[course]++;
}
let ready = [];
for (let i = 0; i < n; i++) {
if (left[i] === 0) ready.push(i);
}
const semesters = [];
let taken = 0;
while (ready.length) {
semesters.push(ready); // take everything that is open
taken += ready.length;
const next = [];
for (const u of ready) {
for (const v of unlocks[u]) {
left[v]--;
if (left[v] === 0) next.push(v); // just unlocked
}
}
ready = next;
}
return taken === n ? semesters : null;
}
const result = plan(5, [[2, 0], [3, 1], [3, 2], [4, 3]]);
result.forEach((courses, i) => {
console.log('Semester ' + (i + 1) + ': ' + courses.join(', '));
});
console.log(plan(2, [[0, 1], [1, 0]]) === null ? 'Impossible: prerequisites loop' : 'ok');Java
import java.util.*;
public class Main {
// Course Schedule: returns the semesters (each a list of courses), or null if impossible.
// prereqs holds pairs {course, prerequisite}, like {1, 0} = "course 1 needs course 0".
static List<List<Integer>> plan(int n, int[][] prereqs) {
List<List<Integer>> unlocks = new ArrayList<>(); // pre -> courses that depend on it
for (int i = 0; i < n; i++) unlocks.add(new ArrayList<>());
int[] left = new int[n]; // prerequisites still unfinished
for (int[] p : prereqs) {
unlocks.get(p[1]).add(p[0]);
left[p[0]]++;
}
List<Integer> ready = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (left[i] == 0) ready.add(i);
}
List<List<Integer>> semesters = new ArrayList<>();
int taken = 0;
while (!ready.isEmpty()) {
semesters.add(ready); // take everything that is open
taken += ready.size();
List<Integer> next = new ArrayList<>();
for (int u : ready) {
for (int v : unlocks.get(u)) {
left[v]--;
if (left[v] == 0) next.add(v); // just unlocked
}
}
ready = next;
}
return taken == n ? semesters : null;
}
public static void main(String[] args) {
var result = plan(5, new int[][]{{2, 0}, {3, 1}, {3, 2}, {4, 3}});
for (int i = 0; i < result.size(); i++) {
List<String> courses = new ArrayList<>();
for (int c : result.get(i)) courses.add(String.valueOf(c));
System.out.println("Semester " + (i + 1) + ": " + String.join(", ", courses));
}
System.out.println(plan(2, new int[][]{{0, 1}, {1, 0}}) == null ? "Impossible: prerequisites loop" : "ok");
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// plan returns the semesters (each a list of courses), or ok=false if impossible.
// prereqs holds pairs {course, prerequisite}, like {1, 0} = "course 1 needs course 0".
func plan(n int, prereqs [][2]int) (semesters [][]int, ok bool) {
unlocks := make([][]int, n) // pre -> courses that depend on it
left := make([]int, n) // prerequisites still unfinished
for _, p := range prereqs {
unlocks[p[1]] = append(unlocks[p[1]], p[0])
left[p[0]]++
}
var ready []int
for i := 0; i < n; i++ {
if left[i] == 0 {
ready = append(ready, i)
}
}
taken := 0
for len(ready) > 0 {
semesters = append(semesters, ready) // take everything that is open
taken += len(ready)
var next []int
for _, u := range ready {
for _, v := range unlocks[u] {
left[v]--
if left[v] == 0 {
next = append(next, v) // just unlocked
}
}
}
ready = next
}
return semesters, taken == n
}
func main() {
result, _ := plan(5, [][2]int{{2, 0}, {3, 1}, {3, 2}, {4, 3}})
for i, courses := range result {
var names []string
for _, c := range courses {
names = append(names, strconv.Itoa(c))
}
fmt.Printf("Semester %d: %s\n", i+1, strings.Join(names, ", "))
}
if _, ok := plan(2, [][2]int{{0, 1}, {1, 0}}); !ok {
fmt.Println("Impossible: prerequisites loop")
} else {
fmt.Println("ok")
}
}Time: O(V + E) · Extra space: O(V + E). Every course and every prerequisite pair is handled once.
Watch out for
- Reversing the pair: in LeetCode's format
[a, b]means "to take a you must take b first", so the arrow goes b → a. - Answering "yes" just because no course is missing from the list. You must check that all courses were actually taken.
- Courses with no prerequisites and no dependants (isolated nodes) are easy to forget. They still count and must be in the answer.
Quick check
- Courses: A needs B, B needs C, C needs A. Can all be completed?
- Yes, in 3 semesters
- Yes, in 1 semester
- No, there is a prerequisite cycle
- Only if we start with B
- In the semester-by-semester method, who can be taken in a semester?
- Only one course at a time
- Any course
- Courses whose prerequisites are all finished
- What does the number of layers (semesters) tell you?
- The most popular course
- The minimum semesters needed
- The number of cycles