KatInterview

Count Activations per Node in a Cascade Graph

Trees & GraphsModel answer
EasyModel answerTrees & Graphsdagtopological-sortpath-counting

Last updated

Given a DAG of task dependencies and one start node, compute how many times each node fires when every activation fans out once along every outgoing edge.

Cascade Activation Counts

A build system models its jobs as a directed acyclic graph. Every node is a job, and an edge u -> v means that each time u runs, it fires v exactly once.

Rules of the cascade:

  • There is a single start node (entry), and it fires exactly once at the beginning.
  • Whenever a node fires, it fires every one of its direct successors once.
  • A node with several incoming edges accumulates the fires it receives from all of its predecessors.

Your goal is to determine how many times each node fires in total.

Input

  • edges: a list of pairs (u, v), each meaning a directed edge u -> v.
  • entry: the ID of the start node.

You may assume the graph has no cycles and that every node appearing in edges is a valid node. IDs may be integers or strings; any hashable type is acceptable, so state your choice.

Example

Edges:

A -> B
B -> C
B -> D
C -> D
D -> E
D -> F
E -> F

Entry: A

Walkthrough:

  • A fires once (given).
  • B fires once (from A).
  • C fires once (from B).
  • D fires twice (once via B, once via C).
  • E fires twice (both fires come from D).
  • F fires four times (two from D, two from E).

Expected result:

A: 1
B: 1
C: 1
D: 2
E: 2
F: 4

Task

Write a Python function:

def count_triggers(edges, entry):
    """Return a mapping from node to its trigger count."""

Requirements:

  • Every node reachable from entry must be handled correctly.
  • It must run efficiently on graphs with up to roughly 10^5 nodes and 10^5 edges.

In your answer, explain your approach, state its time and space complexity, and describe how you handle edge cases such as nodes that cannot be reached from entry, repeated edges, very deep chains, and very large counts.

Hints

Hint 1

Think about what the number of fires of a node means in terms of paths. How does the count of a node relate to the counts of its direct predecessors?

Hint 2

Simulating each fire one by one with a queue can blow up, since counts can double at every layer (e.g., a chain of 50 diamonds yields 2^50 fires). Instead, push a node's whole count to its children once per edge.

Hint 3

To push a count only when it is final, process nodes in topological order (Kahn's algorithm). Compute in-degrees only over nodes reachable from the entry, otherwise an unreachable parent will leave a child stuck with a nonzero in-degree.

Hint 4

Use iterative traversal rather than recursion because a chain of 10^5 nodes exceeds Python's default recursion limit.