KatInterview

Minimum Time to Complete All Build Tasks with Dependencies

Trees & GraphsAuto-graded · 17 test cases
HardAuto-gradedTrees & Graphsgraphstopological sortdynamic programming

Last updated

Tests ability to apply topological ordering (Kahn's algorithm) to schedule parallel tasks with durations and prerequisite chains, computing the earliest completion time.

Minimum Time to Complete All Build Tasks

You are managing a build system. There are n tasks numbered 0 through n - 1. Each task has a duration (the number of time units it takes to execute) and a list of prerequisite tasks that must fully complete before it can begin.

Tasks with no unfinished prerequisites can run in parallel starting at any moment their prerequisites are done.

Given:

  • durations: a list of n positive integers where durations[i] is the time to complete task i.
  • prerequisites: a list of pairs [a, b] meaning task b must fully complete before task a can start.

Return the minimum time (as an integer) at which all tasks have finished, assuming unlimited parallel workers.

If the dependency graph contains a cycle, return -1.

How time works

  • Every task starts as soon as all its prerequisites are done.
  • A task with no prerequisites can start at time 0.
  • The finish time of task i is: (earliest start of i) + durations[i].
  • The earliest start of task i is: max(finish times of all prerequisites of i), or 0 if none.
  • The answer is max(finish times of all tasks).

Constraints

  • 1 <= n <= 2000
  • 1 <= durations[i] <= 1000
  • 0 <= len(prerequisites) <= 10000
  • Each pair [a, b] satisfies 0 <= a, b <= n - 1 and a != b.
  • There may be duplicate edges in prerequisites; treat them as a single dependency.
  • If n == 1 and there are no prerequisites, the answer is simply durations[0].
  • Return -1 if and only if the graph has at least one cycle.

Examples

Example 1

Input: minimum_build_time([3, 2, 5, 1], [[2, 0], [2, 1], [3, 2]])

Output: 9

Example 2

Input: minimum_build_time([4, 3, 6, 2, 5], [[1, 0], [2, 0], [3, 1], [3, 2], [4, 3]])

Output: 17

Example 3

Input: minimum_build_time([7], [])

Output: 7

Hints

Hint 1

Build a directed graph where an edge from b to a means 'b must finish before a starts'. Compute in-degrees for Kahn's algorithm.

Hint 2

Track the earliest finish time for each node. When you process a node in topological order, propagate its finish time to all its dependents: earliest_start[dependent] = max(earliest_start[dependent], finish[current]).

Hint 3

If after Kahn's BFS the number of processed nodes is less than n, a cycle exists — return -1. Otherwise return the maximum finish time across all nodes.