Leetcode #2050: Parallel Courses III
In this guide, we solve Leetcode #2050 Parallel Courses III 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 a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship).
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Graph, Topological Sort, Array, Dynamic Programming
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 = 3, relations = [[1,3],[2,3]], time = [3,2,5]
Output: 8
Explanation: The figure above represents the given graph and the time required to complete each course.
We start course 1 and course 2 simultaneously at month 0.
Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.
Python Solution
class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
g = defaultdict(list)
indeg = [0] * n
for a, b in relations:
g[a - 1].append(b - 1)
indeg[b - 1] += 1
q = deque()
f = [0] * n
ans = 0
for i, (v, t) in enumerate(zip(indeg, time)):
if v == 0:
q.append(i)
f[i] = t
ans = max(ans, t)
while q:
i = q.popleft()
for j in g[i]:
f[j] = max(f[j], f[i] + time[j])
ans = max(ans, f[j])
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
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.