Count Activations per Node in a Cascade Graph
Trees & GraphsModel answerLast 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 edgeu -> 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:
Afires once (given).Bfires once (fromA).Cfires once (fromB).Dfires twice (once viaB, once viaC).Efires twice (both fires come fromD).Ffires four times (two fromD, two fromE).
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
entrymust 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The number of times a node fires equals the number of distinct paths from entry to that node. Each firing of a parent sends exactly one firing along each outgoing edge, so:
count(entry) = 1
count(v) = sum of count(u) over all edges u -> v
This is a dynamic program over a DAG. The only requirement is that count(u) is final before it is passed to u's children, which means processing nodes in topological order.
Why not simulate?
A straightforward BFS that enqueues a node every time it fires is exponential in the worst case. A chain of 50 "diamond" shapes already produces 2^50 firings. The DP touches each edge once regardless of how large the counts are.
Algorithm
- Build adjacency lists from
edges, and register every node, includingentryeven if it appears in no edge. - Find the reachable set from
entrywith an iterative DFS (no recursion, so deep chains are safe). - Compute in-degrees only within the reachable subgraph. This is the most common mistake. If an unreachable node
Xhas an edgeX -> D, counting it would keepD's in-degree above zero forever, soDwould never be processed. Unreachable parents contribute 0 firings, so their edges can be ignored. - Run Kahn's algorithm starting at
entry. When a nodeuis popped, addcount[u]tocount[v]for each childv, then decrementindeg[v]. When it hits 0, enqueuev: all reachable parents have contributed, socount[v]is final. - Validate. If the number of processed nodes is smaller than the reachable set, some node never reached in-degree 0, which implies a cycle. Raise an error instead of returning wrong values.
Unreachable nodes are reported with count 0.
Correctness
- Finality: a node is dequeued only after every reachable in-edge has been applied. Dropping edges from unreachable nodes changes nothing because they add 0.
- Entry has reachable in-degree 0: if a reachable
whad an edgew -> entry, thenentry -> ... -> w -> entrywould be a cycle. - Induction: each processed node's count is the sum of its parents' final counts, which by the recurrence is the number of entry-to-node paths, i.e., its firing count.
On the example: A=1, B=1, C=1, D=1+1=2, E=2, F=2+2=4. This matches the expected output.
Complexity
- Time: O(V + E). Graph construction, DFS, in-degree computation, and Kahn's pass each touch every node and edge a constant number of times. With huge counts, big-integer addition adds a factor proportional to the number of digits. If a modulus such as 10^9 + 7 is requested, apply it when adding.
- Space: O(V + E) for adjacency lists, in-degrees, counts, and the queue.
Edge cases and trade-offs
entryhas no edges: the result is{entry: 1}.- Unreachable nodes or parents: count 0, and they must not block the topological pass (step 3).
- Duplicate edges: treated as separate edges, so
(u, v)listed twice givesva contribution of2 * count[u]. If set semantics are wanted instead, deduplicate first. State whichever assumption you make. - Deep chains (10^5): all traversals are iterative.
- Overflow: Python ints are arbitrary precision. In fixed-width languages, mention 64-bit overflow or modular arithmetic.
- Cycles despite the promise: caught by the processed-count check.
- Alternative approach: a memoized "pull" DFS computing
count(v) = sum(count(p))over parents works too, but it needs a reverse graph and an explicit post-order to avoid recursion. The push-style Kahn approach is simpler and detects cycles for free.
Common mistakes
- Simulating each firing individually (exponential time).
- Counting in-degrees over the whole graph, so children of unreachable nodes are never processed.
- Using recursive DFS and hitting the recursion limit.
- Assuming all nodes are reachable without confirming it.
- Forgetting that
entrymay not appear in any edge.
Python solution
from collections import defaultdict, deque
from typing import Dict, Hashable, Iterable, Tuple
def count_triggers(edges: Iterable[Tuple[Hashable, Hashable]],
entry: Hashable) -> Dict[Hashable, int]:
"""Return a mapping from node to its trigger count.
The count of a node is the number of distinct paths from `entry`.
Unreachable nodes map to 0. Duplicate edges count separately.
Raises ValueError if a cycle is reachable from `entry`.
"""
adj = defaultdict(list)
nodes = {entry}
for u, v in edges:
adj[u].append(v)
nodes.add(u)
nodes.add(v)
# Reachable set via iterative DFS.
reachable = {entry}
stack = [entry]
while stack:
u = stack.pop()
for v in adj.get(u, ()):
if v not in reachable:
reachable.add(v)
stack.append(v)
# In-degrees restricted to the reachable subgraph.
indeg = {n: 0 for n in reachable}
for u in reachable:
for v in adj.get(u, ()):
indeg[v] += 1
# Kahn's algorithm with count propagation.
counts = {n: 0 for n in nodes}
counts[entry] = 1
queue = deque([entry])
processed = 0
while queue:
u = queue.popleft()
processed += 1
cu = counts[u]
for v in adj.get(u, ()):
counts[v] += cu
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
if processed != len(reachable):
raise ValueError("Graph reachable from entry contains a cycle")
return counts
if __name__ == "__main__":
edges = [("A", "B"), ("B", "C"), ("B", "D"), ("C", "D"),
("D", "E"), ("D", "F"), ("E", "F")]
print(count_triggers(edges, "A"))
# {'A': 1, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 4}