Longest Dependency Chain in a Task DAG
Trees & GraphsAuto-graded · 18 test casesLast updated
Find the longest total-duration chain in a task dependency DAG and return its length and task names, using topological-order DP with predecessor tracking.
A build pipeline is made of tasks. Each task is a dictionary with three keys:
"name": a unique string identifying the task"dependencies": a list of names of tasks that must finish before this task can begin"duration": a positive integer, the time this task takes
A task can only start once every task it depends on has finished. Tasks with no unfinished prerequisites may run in parallel. The dependency relationships contain no cycles, and every name listed in "dependencies" refers to a task in the input.
Write a function that finds the bottleneck chain of the pipeline: the sequence of tasks, where each task depends on the previous one, that has the largest total duration.
Return a two-element list [total, path]:
totalis the sum of durations along the longest chain. This is also the earliest time the whole project can be complete.pathis the list of task names on one such chain, ordered from the first task to execute to the last. Each task in the list must directly depend on the one before it.
Details:
- The chain may start at any task with no dependencies and may end at any task. The last task in the input is not necessarily the end of the longest chain.
- Tasks may appear in the input in any order, so a task can list a dependency that appears later in the list.
- If several chains tie for the largest total, returning any one of them is acceptable.
- If the task list is empty, return
[0, []].
Constraints
0 <= len(tasks) <= 10^5- Total number of dependency entries is at most
2 * 10^5. - Task names are unique, non-empty strings.
- Each
durationis a positive integer, and the total fits in a 64-bit integer. - The dependency graph is acyclic and every dependency refers to an existing task.
- The expected running time is linear in the number of tasks plus dependency entries.
Examples
Example 1
Input: longest_dependency_chain([{'name': 'A', 'dependencies': [], 'duration': 3}, {'name': 'B', 'dependencies': [], 'duration': 5}, {'name': 'C', 'dependencies': ['A'], 'duration': 5}])
Output: [8, ['A', 'C']]
Example 2
Input: longest_dependency_chain([{'name': 'A', 'dependencies': [], 'duration': 2}, {'name': 'B', 'dependencies': ['A'], 'duration': 4}, {'name': 'C', 'dependencies': ['B'], 'duration': 3}, {'name': 'D', 'dependencies': ['C'], 'duration': 6}])
Output: [15, ['A', 'B', 'C', 'D']]
Example 3
Input: longest_dependency_chain([{'name': 'A', 'dependencies': [], 'duration': 3}, {'name': 'B', 'dependencies': ['A'], 'duration': 2}, {'name': 'C', 'dependencies': ['A'], 'duration': 7}, {'name': 'D', 'dependencies': ['B', 'C'], 'duration': 4}, {'name': 'E', 'dependencies': ['D'], 'duration': 2}])
Output: [16, ['A', 'C', 'D', 'E']]
Example 4
Input: longest_dependency_chain([{'name': 'A', 'dependencies': [], 'duration': 3}, {'name': 'B', 'dependencies': [], 'duration': 8}, {'name': 'C', 'dependencies': ['A'], 'duration': 2}, {'name': 'D', 'dependencies': ['C'], 'duration': 5}, {'name': 'E', 'dependencies': ['B'], 'duration': 1}, {'name': 'F', 'dependencies': ['D', 'E'], 'duration': 4}])
Output: [14, ['A', 'C', 'D', 'F']]
Hints
Hint 1
Think of each task as a node with a weight. The best chain ending at a task is its own duration plus the best chain ending at one of its prerequisites.
Hint 2
Process tasks in an order where every prerequisite is handled before the tasks that depend on it (topological order, for example Kahn's algorithm with in-degree counts).
Hint 3
While computing the best total ending at each task, remember which prerequisite gave that best value. Start from the task with the overall largest total, follow these links back, then reverse the result.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the longest-path problem on a DAG with weights on nodes. It is hard on general graphs, but on a DAG it can be solved with dynamic programming in topological order.
Let best[v] be the largest total duration of any chain that ends at task v. Then:
best[v] = duration[v] + max(best[u] for u in dependencies of v), or just duration[v] if v has no dependencies.
The answer is the maximum of best[v] over all tasks.
Steps:
- Map task names to indices and build a child list (
dependency -> dependent task) plus an in-degree count for each task. - Run Kahn's algorithm to get a topological order. Start with every task whose in-degree is 0, and release a task when its in-degree drops to 0.
- Initialize
best[v] = duration[v]andprev[v] = None. Walk the tasks in topological order. For each taskuand each dependentc, computebest[u] + duration[c]. If it beatsbest[c], updatebest[c]and setprev[c] = u. - Pick the task with the largest
bestvalue (not necessarily the last one in the input). Followprevlinks back to a task with no predecessor, then reverse the collected names. - For empty input, return
[0, []].
Why it is correct
- Optimal substructure: any chain ending at
vis a chain ending at one of its dependencies, followed byv. So the best chain ending atvextends the best chain of some dependency, and taking the maximum over dependencies is exactly right. - Ordering: in topological order, when we relax the edges leaving
u,best[u]is already final because all ofu's dependencies came earlier. So eachbest[c]is the true maximum once all its dependencies have been processed. - Path recovery:
prev[c]always records the dependency that producedbest[c], so followingprevfrom the overall maximum reproduces a chain whose durations sum to the maximum. - Input order and multiple endpoints: the topological sort removes any dependence on input order, and taking the maximum over all tasks handles multiple sources and sinks.
Complexity
- Time: O(V + E), since each task is queued once and each dependency edge is examined a constant number of times.
- Space: O(V + E) for the child lists, in-degrees,
bestandprevarrays.
Reference solution
from collections import deque
from typing import List, Dict
def longest_dependency_chain(tasks: List[Dict[str, object]]) -> List[object]:
n = len(tasks)
if n == 0:
return [0, []]
index = {task["name"]: i for i, task in enumerate(tasks)}
children = [[] for _ in range(n)]
indegree = [0] * n
for i, task in enumerate(tasks):
for dep in task["dependencies"]:
p = index[dep]
children[p].append(i)
indegree[i] += 1
queue = deque(i for i in range(n) if indegree[i] == 0)
order = []
while queue:
node = queue.popleft()
order.append(node)
for child in children[node]:
indegree[child] -= 1
if indegree[child] == 0:
queue.append(child)
best = [task["duration"] for task in tasks]
prev = [None] * n
for node in order:
for child in children[node]:
candidate = best[node] + tasks[child]["duration"]
if candidate > best[child]:
best[child] = candidate
prev[child] = node
end = max(range(n), key=lambda i: best[i])
total = best[end]
path = []
while end is not None:
path.append(tasks[end]["name"])
end = prev[end]
path.reverse()
return [total, path]