Parallel Courses III — LeetCode 2050 Python Solution
- Problem
- #2050
- Pattern
- Topological Sort
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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).
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.
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(m + n) auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2050. Parallel Courses III is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2050. Parallel Courses III?
- LeetCode 2050. Parallel Courses III is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2050. Parallel Courses III?
- The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 2050. Parallel Courses III?
- The Python solution on this page uses O(m + n) auxiliary space.
- What topics does LeetCode 2050. Parallel Courses III cover?
- LeetCode 2050. Parallel Courses III is tagged Graph, Topological Sort, Array and Dynamic Programming on LeetCode.