Python coding

Earliest finish for dependent tasks

A build has tasks numbered 0 to n - 1; task i takes durations[i] minutes. Each pair [task, needs] in deps means task can only start after needs has finished. Any number of tasks can run at the same time. Return the earliest minute at which every task is finished, or -1 if the dependencies form a cycle.

Durations are positive, pairs may repeat, and with no tasks the answer is 0.

Besides the tests, one large input (3,500 tasks in a chain) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • earliest_finish([3,2,4], [[2,0],[2,1]]) → 7
  • earliest_finish([5,1,1], [[2,1]]) → 5
  • earliest_finish([2,2], [[0,1],[1,0]]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A task starts when its slowest dependency finishes, so you need each dependency's finish time first: process the tasks in topological order.

Hint 2

Kahn's algorithm: start with the tasks that wait on nothing. When a task leaves the queue, offer finish[t] + durations[nxt] to each task it unlocks and keep the maximum.

Hint 3

Tasks run in parallel, so the answer is the largest finish time, not the sum. If fewer than n tasks left the queue, there is a cycle: return -1.

Solution and why it works
pythonO(n + E), E = number of pairs · O(n + E)
from collections import deque


def earliest_finish(durations: list[int], deps: list[list[int]]) -> int:
    n = len(durations)
    unlocks, waiting = [[] for _ in range(n)], [0] * n
    for task, needs in deps:
        unlocks[needs].append(task)
        waiting[task] += 1
    finish = list(durations)                 # with no dependencies a task starts at minute 0
    queue = deque(t for t in range(n) if waiting[t] == 0)
    done = 0
    while queue:
        t = queue.popleft()
        done += 1
        for nxt in unlocks[t]:
            finish[nxt] = max(finish[nxt], finish[t] + durations[nxt])
            waiting[nxt] -= 1
            if waiting[nxt] == 0:
                queue.append(nxt)
    return max(finish, default=0) if done == n else -1

A task's finish time is its duration plus the latest finish among its dependencies: the longest path into it. Kahn's algorithm hands out a task only after all its dependencies, so every finish[t] is final when t leaves the queue, and one pass over the edges is enough: O(n + E). Take max over incoming edges, not the first or last arrival, and the largest finish overall, since tasks overlap. Fewer than n tasks processed means a cycle.