Parallel Courses Problem
Description
LeetCode Problem 1136.
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCourse_i, nextCourse_i], representing a prerequisite relationship between course prevCourse_i and course nextCourse_i: course prevCourse_i has to be taken before course nextCourse_i.
In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking.
Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.
Example 1:

Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 1 and 2.
In the second semester, you can take course 3.
Example 2:

Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: No course can be studied because they are prerequisites of each other.
Constraints:
1 <= n <= 50001 <= relations.length <= 5000relations[i].length == 21 <= prevCourse_i, nextCourse_i <= nprevCourse_i != nextCourse_i- All the pairs
[prevCourse_i, nextCourse_i]are unique.
Solution
Approach: Topological Sort, One Layer per Semester
Treat each course as a node and each relation prev -> next as a directed edge, and count each course's in-degree (how many prerequisites it still waits for).
Taking as many courses as possible each semester is always best, since taking a course earlier never delays anything. So we simulate it semester by semester (Kahn's algorithm, processed in layers):
- Semester 1 is every course with in-degree
0. - After a semester, each course taken lowers the in-degree of the courses that depend on it. Every course whose in-degree drops to
0has now had all its prerequisites taken, so it goes into the next semester. - Stop when a semester would be empty.
The number of layers is the answer, which is the length of the longest chain of prerequisites. If the relations contain a cycle, the courses on it (and everything after them) never reach in-degree 0, so fewer than n courses are taken in total and we return -1.
Complexity: O(n + m) time and space for n courses and m relations: each course and each edge is handled once.
class Solution:
def minimumSemesters(self, n: int, relations: List[List[int]]) -> int:
graph = [[] for _ in range(n + 1)]
indeg = [0] * (n + 1)
for prev, nxt in relations:
graph[prev].append(nxt)
indeg[nxt] += 1
# Semester 1: every course without prerequisites.
layer = [c for c in range(1, n + 1) if indeg[c] == 0]
taken = 0
semesters = 0
while layer:
semesters += 1
taken += len(layer)
nxt_layer = []
for c in layer:
for d in graph[c]:
indeg[d] -= 1
if indeg[d] == 0: # its last prerequisite was taken this semester
nxt_layer.append(d)
layer = nxt_layer
return semesters if taken == n else -1 # courses left over sit on a cycle