Calculate Cumulative Task Weights in a Dependency Graph
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests graph traversal and dynamic programming on DAGs to compute propagated weight contributions through dependency chains.
You are analyzing a system where tasks form a directed acyclic graph based on their dependencies. Each task has a base weight, and you need to calculate how much total weight flows through each task when accounting for all tasks that rely on it.
Write a function that computes the cumulative weight for every task. The cumulative weight of a task equals its own base weight plus the sum of cumulative weights of all tasks that depend on it (directly or indirectly).
Input
n: An integer representing the number of tasks, labeled from0ton-1base_weights: A list of integers wherebase_weights[i]is the base weight of taskiedges: A list of pairs[a, b]where taskbdepends on taska(meaning weight flows frombback toa)
Output
Return a list of integers where the value at index i is the cumulative weight of task i.
Constraints
1 <= n <= 10^40 <= len(edges) <= 10^5- All base weights are non-negative integers
- The graph is guaranteed to be acyclic (no circular dependencies)
- If a task appears in multiple dependency paths, its cumulative weight is counted once for each path
Notes
- Tasks with no dependents have cumulative weight equal to their base weight
- The graph may contain disconnected components
- When multiple tasks depend on the same task, that task accumulates weight contributions from all its dependents
Examples
Example 1
Input: calculate_cumulative_weights(3, [1, 2, 3], [[0, 1], [1, 2]])
Output: [6, 5, 3]
Hints
Hint 1
Start by building an adjacency list where each task points to all tasks that depend on it
Hint 2
Process tasks in an order where all dependents are computed before their dependencies - reverse topological order works well
Hint 3
Use Kahn's algorithm for topological sorting to avoid recursion depth issues with long chains
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires computing a value for each node in a DAG where each node's value depends on the values of nodes that reference it. We solve this using dynamic programming combined with topological sorting.
The key insight is that a task's cumulative weight equals its base weight plus the sum of cumulative weights from all tasks that depend on it. This creates a dependency: we must compute dependent tasks before we can compute the tasks they depend on.
Algorithm steps:
- Build an adjacency list where each task points to the tasks it depends on (reversing the edge direction from the problem statement)
- Track the in-degree (number of dependents) for each task
- Use Kahn's algorithm to generate a topological ordering, starting from tasks with no dependents (in-degree 0)
- Process tasks in topological order: for each task, propagate its cumulative weight to all tasks it depends on
- When a task's in-degree reaches 0, all its dependents have been processed, so add it to the queue
Why this works:
Processing in topological order ensures that when we compute a task's cumulative weight, all tasks depending on it have already contributed their weights. Starting from tasks with no dependents (sinks in the dependency graph) and working backward guarantees this property.
When a task appears in multiple dependency paths, it correctly accumulates weight from each path separately, as each dependent task adds its cumulative weight independently.
Complexity:
- Time: O(V + E) where V is the number of tasks and E is the number of edges. We traverse each node and edge a constant number of times.
- Space: O(V + E) for the adjacency list, plus O(V) for tracking in-degrees, the queue, and the result array.
from collections import defaultdict, deque
from typing import List
def calculate_cumulative_weights(n: int, base_weights: List[int], edges: List[List[int]]) -> List[int]:
# Build adjacency list: graph[b] = list of tasks that b depends on
graph = defaultdict(list)
in_degree = [0] * n
for a, b in edges:
graph[b].append(a) # b depends on a, so a receives weight from b
in_degree[a] += 1
# Initialize cumulative weights with base weights
cumulative = base_weights[:]
# Topological sort using Kahn's algorithm
queue = deque()
for i in range(n):
if in_degree[i] == 0:
queue.append(i)
# Process nodes in topological order
while queue:
node = queue.popleft()
# For each task that the current node depends on
for dependency in graph[node]:
# Propagate this node's cumulative weight to its dependency
cumulative[dependency] += cumulative[node]
# Decrease in-degree and add to queue when ready
in_degree[dependency] -= 1
if in_degree[dependency] == 0:
queue.append(dependency)
return cumulative