Earliest Finish Time for a Dependent Job Pipeline
Trees & GraphsAuto-graded · 18 test casesLast updated
Compute the shortest total time to finish all jobs with unlimited parallelism by finding the longest weighted path in a dependency graph, returning -1 if a cycle exists.
Job Pipeline Scheduling
A project consists of n jobs, labeled 0 through n-1. Job i takes durations[i] units of time to run. Some jobs depend on others: a dependency [a, b] means job a must be completely finished before job b is allowed to begin.
You have as many workers as you need, so any number of jobs can run at the same time, as long as every job they depend on has already finished. A job starts at the earliest moment all of its dependencies are done (or at time 0 if it has none).
Return the smallest total time needed for every job to finish. If the dependencies contain a cycle, which means not every job can ever be completed, return -1.
Function
def earliest_finish_time(n: int, durations: List[int], dependencies: List[List[int]]) -> int:
Parameters
n: the number of jobs.durations: a list of lengthn, wheredurations[i]is the running time of jobi.dependencies: a list of pairs[a, b], each meaning jobamust finish before jobbcan start.
Rules and edge cases
- Jobs with no dependencies start at time
0. - The graph may consist of several disconnected parts; the answer is the time at which the last job in any part finishes.
- A pair
[a, a](a job depending on itself) is a cycle, so the answer is-1. - The same pair may appear more than once; duplicates do not change the result.
- A cycle anywhere in the graph, even among jobs unrelated to the rest, makes the answer
-1. - A duration of
0is allowed and simply passes through the finish time of its dependencies.
Constraints
1 <= n <= 10,0000 <= len(dependencies) <= 100,000durationshas lengthn- Every job label in
dependenciesis in the range0ton-1 - Return
-1if the dependencies contain a cycle
Examples
Example 1
Input: earliest_finish_time(3, [3, 2, 5], [[0, 2], [1, 2]])
Output: 8
Example 2
Input: earliest_finish_time(2, [1, 1], [[0, 1], [1, 0]])
Output: -1
Hints
Hint 1
Treat each dependency [a, b] as a directed edge a -> b. A job's finish time is its own duration plus the latest finish time among the jobs it depends on.
Hint 2
You need to process jobs so that all of a job's dependencies are finalized before the job itself. A topological ordering (for example Kahn's algorithm with in-degrees) provides exactly that.
Hint 3
If the topological process cannot visit all n jobs, some jobs sit on or behind a cycle, so return -1. Otherwise the answer is the maximum finish time over all jobs.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of the jobs as nodes in a directed graph, with an edge a -> b for every dependency [a, b]. Because workers are unlimited, a job begins the moment its slowest dependency finishes. That gives the recurrence:
finish[v] = durations[v]ifvhas no dependenciesfinish[v] = durations[v] + max(finish[u])over all dependenciesuofv
The total time is the maximum finish value over all jobs. This is the longest weighted path in the graph (the critical path).
Longest path is hard in general graphs, but in a DAG it can be computed by dynamic programming in topological order. We use Kahn's algorithm:
- Build an adjacency list and an in-degree count for each job.
- Start
finish[i] = durations[i], and enqueue all jobs with in-degree 0. - Pop a job
u, count it as processed, and update the running maximum withfinish[u]. For each jobvthat depends onu, setfinish[v] = max(finish[v], finish[u] + durations[v])and decrement its in-degree. When the in-degree hits 0, enqueuev. - If fewer than
njobs were processed, a cycle exists, so return-1. Otherwise return the maximum finish time.
Why it is correct
A job is enqueued only after all of its incoming edges have been relaxed, and each source of those edges was popped earlier with its finish time already final. By induction, finish[v] equals the recurrence value when v is popped. Starting every job as soon as its dependencies finish is both feasible and the earliest possible, so the maximum finish time is optimal.
Jobs on a cycle, and jobs downstream of one, never reach in-degree 0, so they are never processed. Hence processed < n exactly when a cycle exists (a self-dependency is also caught this way). Duplicate edges increment and decrement the in-degree the same number of times, so they cause no problems. Disconnected parts are all handled because every source is seeded in the queue.
Complexity
With E = len(dependencies):
- Time:
O(n + E), since each job is enqueued once and each edge is relaxed once. - Space:
O(n + E)for the adjacency list, plusO(n)for in-degrees, finish times, and the queue.
Reference solution
from collections import deque
from typing import List
def earliest_finish_time(n: int, durations: List[int], dependencies: List[List[int]]) -> int:
graph = [[] for _ in range(n)]
indegree = [0] * n
for a, b in dependencies:
graph[a].append(b)
indegree[b] += 1
finish = list(durations)
queue = deque(i for i in range(n) if indegree[i] == 0)
processed = 0
answer = 0
while queue:
u = queue.popleft()
processed += 1
answer = max(answer, finish[u])
for v in graph[u]:
finish[v] = max(finish[v], finish[u] + durations[v])
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return -1 if processed != n else answer