Leetcode #1494: Parallel Courses II
In this guide, we solve Leetcode #1494 Parallel Courses II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Bit Manipulation, Graph, Dynamic Programming, Bitmask
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2
Output: 3
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
Python Solution
class Solution:
def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:
d = [0] * (n + 1)
for x, y in relations:
d[y] |= 1 << x
q = deque([(0, 0)])
vis = {0}
while q:
cur, t = q.popleft()
if cur == (1 << (n + 1)) - 2:
return t
nxt = 0
for i in range(1, n + 1):
if (cur & d[i]) == d[i]:
nxt |= 1 << i
nxt ^= cur
if nxt.bit_count() <= k:
if (nxt | cur) not in vis:
vis.add(nxt | cur)
q.append((nxt | cur, t + 1))
else:
x = nxt
while nxt:
if nxt.bit_count() == k and (nxt | cur) not in vis:
vis.add(nxt | cur)
q.append((nxt | cur, t + 1))
nxt = (nxt - 1) & x
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.