Parallel Courses
Medium
Topics
You are given n courses labelled 0 to n - 1 and a list of edges where edges[i] = [a, b] means course a must be taken before course b.
In one semester you may take any number of courses, as long as every prerequisite of each one was completed in an earlier semester.
Return the minimum number of semesters needed to take all courses, or -1 if it is impossible.
Example 1
[before, after]; the arrow points at the later course.Input: n = 3, edges = [[0,1],[0,2]] Output: 2 Explanation: Take course 0 in semester 1, then courses 1 and 2 together in semester 2.
Example 2
-1, because a cycle leaves 3 course(s) unreachable.Input: n = 3, edges = [[0,1],[1,2],[2,0]] Output: -1 Explanation: The three courses form a cycle, so no valid order exists.
Constraints
- 1 <= n <= 5000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- All pairs are distinct
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because a semester has unlimited width, the only thing that costs time is depth: the answer is the number of levels in a layered topological order, which equals the longest prerequisite chain. Run Kahn's algorithm but drain the queue one full level at a time and count the levels. If some course never reaches in-degree zero it sits on a cycle, so the answer is -1.
Approach
- Build an adjacency list and an in-degree array from the edge list.
- Seed a queue with every course of in-degree zero. Those are exactly the courses available in semester 1.
- Process the queue level by level: snapshot its current size, pop that many courses, and decrement their neighbours' in-degrees, pushing any that reach zero. Increment the semester counter once per level.
- Count how many courses were popped in total. If that is less than
n, a cycle blocked the rest, so return -1; otherwise return the level count.
from collections import deque
class Solution:
def minimumSemesters(self, n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges:
adj[a].append(b)
indeg[b] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
semesters = 0
taken = 0
while q:
semesters += 1
for _ in range(len(q)):
cur = q.popleft()
taken += 1
for nxt in adj[cur]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
q.append(nxt)
return semesters if taken == n else -1Dry Run
n = 3, relations 0 -> 1 and 0 -> 2
indeg [0, 1, 1] frontier [0]
semester 1 take [0] done 1 next frontier [1, 2]
semester 2 take [1, 2] done 3 next frontier []
done 3 of 3
answer 2 -- not 3, even though there are 3 courses
n = 3, relations 0 -> 1, 1 -> 2, 2 -> 0
indeg [1, 1, 1] frontier [] -- nothing has in-degree 0
the loop never runs: semesters 0, done 0
answer -1
The whole point is that the answer counts LEVELS, not nodes. Courses 1 and 2 have
no dependency on each other, so they are taken together, and returning the number
of courses processed would give 3 instead of 2.
The frontier is rebuilt as a whole list per semester rather than popped one at a
time, which is what keeps the levels separate. Reading a queue length live inside
the loop instead merges semesters together and undercounts.
`done == n` is the cycle check and it is not optional. The cyclic graph above
fails loudly only because it is entirely cyclic; a graph with a cycle plus a free
course would drain the free part and return a small positive number that looks
like a real answer.
An edge case worth stating: with no relations at all, n = 3 answers 1, not 0. Three
independent courses still take one semester.Complexity
- Time — O(V + E) — each course and edge is handled once.
- Space — O(V + E) for the adjacency list, in-degrees, and queue.
Common Pitfalls
- Reading the queue length inside the loop instead of snapshotting it first merges semesters together and undercounts the answer.
- Do not return the number of popped courses. The answer is the number of levels, not the number of nodes.
- The cycle check is mandatory. Without the
taken == ntest a cyclic graph silently returns a small positive number. - An isolated course with no prerequisites still needs one semester, so an empty edge list answers 1, not 0.
Full Solution — all languages
class Solution:
def minimumSemesters(self, n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for a, b in edges:
adj[a].append(b)
indeg[b] += 1
frontier = [i for i in range(n) if indeg[i] == 0]
semesters = 0
done = 0
while frontier:
semesters += 1
nxt = []
for course in frontier:
done += 1
for after in adj[course]:
indeg[after] -= 1
if indeg[after] == 0:
nxt.append(after)
frontier = nxt
return semesters if done == n else -1import java.util.*;
class Solution {
public int minimumSemesters(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
indeg[e[1]]++;
}
List<Integer> frontier = new ArrayList<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) frontier.add(i);
int semesters = 0, done = 0;
while (!frontier.isEmpty()) {
semesters++;
List<Integer> next = new ArrayList<>();
for (int course : frontier) {
done++;
for (int after : adj.get(course)) {
if (--indeg[after] == 0) next.add(after);
}
}
frontier = next;
}
return done == n ? semesters : -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minimumSemesters(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
vector<int> indeg(n, 0);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
indeg[e[1]]++;
}
vector<int> frontier;
for (int i = 0; i < n; i++) if (indeg[i] == 0) frontier.push_back(i);
int semesters = 0, done = 0;
while (!frontier.empty()) {
semesters++;
vector<int> next;
for (int course : frontier) {
done++;
for (int after : adj[course]) {
if (--indeg[after] == 0) next.push_back(after);
}
}
frontier = next;
}
return done == n ? semesters : -1;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/ var minimumSemesters = function(n, edges) {
const adj = Array.from({ length: n }, () => []);
const indeg = new Array(n).fill(0);
for (const e of edges) {
adj[e[0]].push(e[1]);
indeg[e[1]]++;
}
let frontier = [];
for (let i = 0; i < n; i++) if (indeg[i] === 0) frontier.push(i);
let semesters = 0, done = 0;
while (frontier.length) {
semesters++;
const next = [];
for (const course of frontier) {
done++;
for (const after of adj[course]) {
if (--indeg[after] === 0) next.push(after);
}
}
frontier = next;
}
return done === n ? semesters : -1;
};