KatInterview

Earliest Finish Time for a Dependent Task Pipeline

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphdag

Last 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, where n = len(durations)
  • durations[i] >= 0
  • Every pair [a, b] in prerequisites satisfies 0 <= a, b < n
  • prerequisites may 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.