#2050

Parallel Courses III

Hard
ArrayDynamic ProgrammingGraph TheoryTopological SortGraph TheoryTopological SortDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal solution uses dynamic programming and topological sorting to efficiently calculate the minimum time required to complete all courses. By processing courses in order of their prerequisites, we can ensure that we always know when a course can be started.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph from the relations and an indegree array to track prerequisites.
  2. 2Step 2: Use a queue to perform a topological sort, processing courses with no prerequisites first.
  3. 3Step 3: For each course processed, update the minimum time required for its dependent courses.
solution.py28 lines
1# Full working Python code
2from collections import deque
3
4class Solution:
5    def minimumTime(self, n, relations, time):
6        graph = [[] for _ in range(n)]
7        indegree = [0] * n
8        for prev, next in relations:
9            graph[prev - 1].append(next - 1)
10            indegree[next - 1] += 1
11
12        min_time = [0] * n
13        queue = deque()
14
15        for i in range(n):
16            if indegree[i] == 0:
17                queue.append(i)
18                min_time[i] = time[i]
19
20        while queue:
21            course = queue.popleft()
22            for next_course in graph[course]:
23                indegree[next_course] -= 1
24                min_time[next_course] = max(min_time[next_course], min_time[course] + time[next_course])
25                if indegree[next_course] == 0:
26                    queue.append(next_course)
27
28        return max(min_time)

Complexity note: The complexity is O(n + m) where n is the number of courses and m is the number of relations, as we process each course and each relation once.

  • 1Courses can be taken simultaneously if prerequisites are met.
  • 2Topological sorting helps in determining the order of course completion.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.