KatInterview

Calculate Cumulative Task Weights in a Dependency Graph

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphsdagtopological-sort

Last 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 from 0 to n-1
  • base_weights: A list of integers where base_weights[i] is the base weight of task i
  • edges: A list of pairs [a, b] where task b depends on task a (meaning weight flows from b back to a)

Output

Return a list of integers where the value at index i is the cumulative weight of task i.

Constraints

  • 1 <= n <= 10^4
  • 0 <= 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