KatInterview

Earliest Finish Time for a Dependent Job Pipeline

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstopological-sortdaglongest-path

Last 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 length n, where durations[i] is the running time of job i.
  • dependencies: a list of pairs [a, b], each meaning job a must finish before job b can 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 0 is allowed and simply passes through the finish time of its dependencies.

Constraints

  • 1 <= n <= 10,000
  • 0 <= len(dependencies) <= 100,000
  • durations has length n
  • Every job label in dependencies is in the range 0 to n-1
  • Return -1 if 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.