Earliest Finish Time for a Dependent Task Pipeline
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the minimum time to complete all tasks with durations and prerequisites under unlimited parallelism, or detect a circular dependency, using longest path in a DAG with topological ordering.
Scheduling Dependent Modules
A training program consists of n modules numbered 0 to n - 1. Module i takes durations[i] hours to complete.
Some modules have requirements. Each entry [a, b] in prerequisites means module b must be completely finished before module a is allowed to begin.
There is no limit on how many modules can be worked on at the same time. A module starts at the earliest moment all of its required modules are done (at time 0 if it has none).
Return the minimum total number of hours needed until every module is finished. If the requirements contain a circular dependency so that not all modules can ever be completed, return -1.
Notes
- A circular dependency anywhere in the graph, even among only some modules, means the answer is
-1. - A requirement of a module on itself (
[i, i]) is a circular dependency. - The same requirement pair may appear more than once.
- Durations may be
0.
Constraints
1 <= n <= 10^4, wheren = len(durations)durations[i] >= 0- Every pair
[a, b]inprerequisitessatisfies0 <= a, b < n prerequisitesmay be empty
Examples
Example 1
Input: min_completion_hours([3, 2, 5], [[2, 0], [2, 1]])
Output: 8
Example 2
Input: min_completion_hours([2, 2], [[0, 1], [1, 0]])
Output: -1
Hints
Hint 1
Treat each module as a node and each pair [a, b] as a directed edge from b to a. Be careful about the direction.
Hint 2
A module can only start once its slowest prerequisite has finished, so combine prerequisite finish times with max, not sum.
Hint 3
Process modules in topological order (Kahn's algorithm). If fewer than n modules get processed, there is a cycle, so return -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the modules as a directed graph: each pair [a, b] becomes an edge b -> a. Because parallelism is unlimited, a module begins exactly when its last prerequisite finishes, so:
finish[i] = durations[i] + max(finish[p] for p in prerequisites of i) (max over empty = 0)
The answer is the largest finish[i], which is the longest weighted path in the graph (the critical path).
To evaluate this, process the modules in topological order using Kahn's algorithm:
- Build the adjacency list and in-degree counts from the pairs.
- Initialize
completion[i] = durations[i]and enqueue all modules with in-degree 0. - When a module is popped, for each module that depends on it, update
completion[next] = max(completion[next], completion[cur] + durations[next]), then decrement its in-degree and enqueue it if it reaches 0. - If fewer than
nmodules were processed, a cycle exists, so return-1. Otherwise returnmax(completion).
Why it is correct
- A module is enqueued only after all of its prerequisites have been popped and have relaxed it, so its
completionvalue is final when it is processed. - A module cannot start before its latest prerequisite finishes, and nothing forces it to start later, so the earliest-start schedule is optimal and the total time is the maximum finish.
- Modules on a cycle, and everything downstream of one, never reach in-degree 0, so the processed count falls below
nand-1is returned. Self-loops and duplicate edges are handled consistently since each copy adds one to the in-degree and removes one when relaxed.
Complexity
- Time: O(V + E)
- Space: O(V + E)
Reference solution
from collections import deque
from typing import List
def min_completion_hours(durations: List[int], prerequisites: List[List[int]]) -> int:
n = len(durations)
graph = [[] for _ in range(n)]
indegree = [0] * n
for course, prerequisite in prerequisites:
graph[prerequisite].append(course)
indegree[course] += 1
completion = list(durations)
queue = deque(i for i in range(n) if indegree[i] == 0)
processed = 0
while queue:
course = queue.popleft()
processed += 1
for following in graph[course]:
completion[following] = max(
completion[following], completion[course] + durations[following]
)
indegree[following] -= 1
if indegree[following] == 0:
queue.append(following)
return max(completion) if processed == n else -1