Parallel Courses III — LeetCode 2050 Python Solution

HardGraphTopological SortArrayDynamic Programming
Problem
#2050
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(m + n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview