DAG Task Propagation Counts

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a directed dependency graph of workflow stages and a starting stage entry, compute how many times every stage fires.

  • edges is a list of directed pairs (u, v), indicating an outgoing link u -> v. Stage identifiers can be any hashable Python value (such as strings or integers).
  • Repeated (u, v) pairs in edges represent the same link and must be deduplicated so u triggers v at most once per firing of u.
  • Execution begins by firing entry once (1). Whenever a stage u fires once, every distinct outgoing neighbor v of u fires once — so a reachable stage's total count equals the sum of counts across its reachable incoming neighbors (plus 1 for entry).

Implement count_triggers(edges, entry) -> Dict[Hashable, int] following these rules:

  1. Complete key set: Return a dictionary containing entry together with every node appearing anywhere in edges.
  2. Unreachable nodes: Any node that cannot be reached from entry never fires and maps to 0 (and must never block reachable nodes that share a child with it).
  3. Reachable cycle check: If any cycle is reachable from entry (including a self-loop or a cycle passing through entry), raise ValueError. Cycles inside components unreachable from entry never fire and simply map to 0.

Examples

Example 1

edges = [
    ("ingest", "parse"),
    ("ingest", "audit"),
    ("parse", "enrich"),
    ("audit", "enrich"),
    ("enrich", "notify"),
    ("parse", "notify"),
]
count_triggers(edges, "ingest")

Output:

{"ingest": 1, "parse": 1, "audit": 1, "enrich": 2, "notify": 3}

Walk-through: "ingest" fires once (1), triggering "parse" (1) and "audit" (1). "enrich" sums "parse" and "audit" (1 + 1 = 2). "notify" sums "enrich" (2) and "parse" (1), firing 3 times in total.

Example 2

edges = [(10, 20), (10, 20), (20, 30), (99, 20), (40, 50)]
count_triggers(edges, 10)

Output:

{10: 1, 20: 1, 30: 1, 99: 0, 40: 0, 50: 0}

Walk-through: The repeated (10, 20) tuple counts as one link, so 10, 20, and 30 each fire 1 time. Neither 99 (an unreachable parent of 20) nor 40 -> 50 can be reached from 10, so 99, 40, and 50 all map to 0.

Constraints

  • 0 <= len(edges) <= 10^5, with up to 10^5 distinct nodes.
  • Node IDs are arbitrary hashable values (str, int, etc.).
  • Must run in linear O(V + E) graph operations without hitting Python's recursion limit on 10^5-node chains or overflowing 64-bit integer bounds when diamond chains double counts exponentially.

Step-by-step walkthrough

  1. Restate the problem and edge rules

    We are given a directed acyclic graph (DAG) — a network of one-way dependency arrows with no loops that lead back to where they started — along with a single starting node entry. Initially, entry is triggered 1 time, and every time any node u is triggered, each of its outgoing neighbors v is triggered 1 time.

    Sample graph (entry = "ingest"):
    
                   +---> parse (1) ---+---> notify (3)
                  /         \        /
        ingest (1)           v      /
                  \      enrich (2)+
                   \        ^
                    +---> audit (1)
    

    Before writing code, we make every implicit rule explicit:

    • Node IDs: any hashable Python value (strings like "ingest", integers like 10, etc.).
    • Output keys: every node mentioned in edges, plus entry itself. Any node that entry cannot reach never fires and maps to 0.
    • Duplicate edges: if (10, 20) appears twice in edges, 20 is still a single outgoing neighbor of 10, so we deduplicate repeated (u, v) pairs.
    • Reachable cycles: although valid inputs are acyclic, if a cycle is reachable from entry (so counts would loop forever), we detect it and raise ValueError.
  2. Why literal event simulation blows up exponentially

    The most direct idea is to simulate every single trigger event with a stack or queue: pop a node, add 1 to its count, and push all of its children.

    def simulate_events(children, entry):
        counts = {}
        pending = [entry]
        while pending:
            u = pending.pop()
            counts[u] = counts.get(u, 0) + 1
            for v in children.get(u, []):
                pending.append(v)
        return counts
    

    Why is this too slow for 100,000 edges? Because its work equals the sum of trigger counts, which can double every four edges in a chain of diamonds:

    s0 ---> a0 ---> s1 ---> a1 ---> s2 ... ---> sk
      \    /          \    /
       b0-+            b1-+
    
    counts: s0=1, s1=2, s2=4, s3=8, ..., sk = 2^k
    

    With 100,000 edges we can chain k = 25,000 diamonds, making the last node fire 2^25000 times! Instead of simulating individual events, we must propagate whole numbers once per edge.

  3. Key idea: sum parent counts in topological order

    Every trigger arriving at node v comes from one firing of one reachable parent p. Therefore, once we know the final trigger count of every parent of v, v's total count is just their sum:

    count(entry) = 1
    count(v)     = sum of count(p) over all reachable parents p of v
    

    This formula works in one pass if we visit every parent before visiting any of its children — an ordering called a topological order. We find it using Kahn's algorithm:

    1. Compute each node's in-degree (how many incoming edges from reachable parents it is still waiting on).
    2. Put nodes with indegree == 0 into a queue.
    3. Pop u: because indegree[u] == 0, all of u's parents have already added their counts to u, so counts[u] is final! For each child v, add counts[u] to counts[v] and decrement indegree[v]; when indegree[v] hits 0, push v into the queue.
  4. Build deduplicated adjacency lists and find reachable nodes

    We start with two clean helpers:

    • build_children(edges) ensures every node in edges appears as a key in children (even sink nodes with no outgoing edges) and uses seen_edges so a duplicate (u, v) tuple is stored only once.
    • reachable_from(children, entry) finds the set of nodes entry can actually reach. We use an explicit stack rather than recursion because a straight line of 100,000 nodes would crash Python's default 1,000-frame recursion limit.
    from typing import Dict, Hashable, List, Set, Tuple
    from collections import deque
    
    
    def build_children(edges: List[Tuple[Hashable, Hashable]]) -> Dict[Hashable, List[Hashable]]:
        """Build adjacency lists u -> [v, ...]; include every node and deduplicate repeated edges."""
        # children: maps each node -> list of distinct outgoing neighbors, e.g. {"ingest": ["parse", "audit"]}.
        children: Dict[Hashable, List[Hashable]] = {}
        # seen_edges: set of (u, v) pairs already added so duplicate edges fire only once.
        seen_edges: Set[Tuple[Hashable, Hashable]] = set()
        for u, v in edges:
            if u not in children:
                children[u] = []
            if v not in children:
                children[v] = []
            if (u, v) in seen_edges:
                continue
            seen_edges.add((u, v))
            children[u].append(v)
        return children
    
    
    def reachable_from(children: Dict[Hashable, List[Hashable]], entry: Hashable) -> Set[Hashable]:
        """Return all nodes reachable from entry (including entry) using an explicit DFS stack."""
        # Iterative stack avoids Python's ~1000 recursion limit on chains of 100,000 nodes.
        reached: Set[Hashable] = {entry}
        stack: List[Hashable] = [entry]
        while stack:
            u = stack.pop()
            for v in children[u]:
                if v not in reached:
                    reached.add(v)
                    stack.append(v)
        return reached
    
  5. Count in-degrees inside the reachable subgraph only

    Here is the subtle bug that catches many candidates. Suppose the graph has an unreachable node X pointing into a reachable node D, or an unreachable node Z pointing into entry:

    Z (unreachable) ---> A (entry) ---> B ---> D <--- X (unreachable)
                                                |
                                                v
                                                E
    

    If we counted Z -> A and X -> D in indegree, A would start with indegree = 1 (never entering the queue!), and D would wait forever for X to decrement its indegree before forwarding its count to E.

    The fix is simple: count indegree using only edges (u, v) where u is in reached. Unreachable parents never fire, contribute 0, and should never be waited on. Notice also that if u is in reached, every child v in children[u] is automatically in reached too!

    def compute_reachable_indegrees(
        children: Dict[Hashable, List[Hashable]],
        reached: Set[Hashable],
    ) -> Dict[Hashable, int]:
        indegree: Dict[Hashable, int] = {}
        for u in reached:
            indegree[u] = 0
        for u in reached:
            for v in children[u]:
                indegree[v] += 1
        return indegree
    
  6. Propagate counts and trace the sample DAG

    Now we initialize counts[node] = 0 for all nodes and counts[entry] = 1, enqueue every reachable node with indegree == 0, and run Kahn's sweep. At the end, we check processed != len(reached): if any reachable node never dropped to indegree == 0 (including when a cycle passes right through entry, giving entry a positive reachable indegree), a cycle is reachable from entry and we raise ValueError.

    Let us trace Example 1 (ingest->parse, ingest->audit, parse->enrich, audit->enrich, enrich->notify, parse->notify, entry = "ingest"):

    Initial state:
      reached  = {ingest, parse, audit, enrich, notify}
      indegree = {ingest:0, parse:1, audit:1, enrich:2, notify:2}
      counts   = {ingest:1, parse:0, audit:0, enrich:0, notify:0}
      queue    = [ingest]
    
    Step  Pop u (final count)   Updates to children (counts, indegree)               Queue after step
    ----  --------------------  ---------------------------------------------------  ----------------
    1     ingest (1)            parse:  count 0+1=1, indeg 1->0 (enqueue parse)
                                audit:  count 0+1=1, indeg 1->0 (enqueue audit)      [parse, audit]
    2     parse (1)             enrich: count 0+1=1, indeg 2->1 (waits on audit)
                                notify: count 0+1=1, indeg 2->1 (waits on enrich)    [audit]
    3     audit (1)             enrich: count 1+1=2, indeg 1->0 (enqueue enrich)     [enrich]
    4     enrich (2)            notify: count 1+2=3, indeg 1->0 (enqueue notify)     [notify]
    5     notify (3)            (no children)                                        []
    
    processed = 5 == len(reached) -> valid DAG!
    Final counts: {ingest: 1, parse: 1, audit: 1, enrich: 2, notify: 3}
    
  7. Complete solution

    from typing import Dict, Hashable, List, Set, Tuple
    from collections import deque
    
    
    def build_children(edges: List[Tuple[Hashable, Hashable]]) -> Dict[Hashable, List[Hashable]]:
        """Build adjacency lists u -> [v, ...]; include every node and deduplicate repeated edges."""
        # children: maps each node -> list of distinct outgoing neighbors, e.g. {"ingest": ["parse", "audit"]}.
        children: Dict[Hashable, List[Hashable]] = {}
        # seen_edges: set of (u, v) pairs already added so duplicate edges fire only once.
        seen_edges: Set[Tuple[Hashable, Hashable]] = set()
        for u, v in edges:
            if u not in children:
                children[u] = []
            if v not in children:
                children[v] = []
            if (u, v) in seen_edges:
                continue
            seen_edges.add((u, v))
            children[u].append(v)
        return children
    
    
    def reachable_from(children: Dict[Hashable, List[Hashable]], entry: Hashable) -> Set[Hashable]:
        """Return all nodes reachable from entry (including entry) using an explicit DFS stack."""
        # Iterative stack avoids Python's ~1000 recursion limit on chains of 100,000 nodes.
        reached: Set[Hashable] = {entry}
        stack: List[Hashable] = [entry]
        while stack:
            u = stack.pop()
            for v in children[u]:
                if v not in reached:
                    reached.add(v)
                    stack.append(v)
        return reached
    
    
    def count_triggers(edges: List[Tuple[Hashable, Hashable]], entry: Hashable) -> Dict[Hashable, int]:
        """Return a mapping from node to the number of times it is triggered.
    
        edges: (u, v) pairs, each meaning u -> v. Node ids may be any hashable value
        (strings, integers, ...). A repeated (u, v) pair is the same edge and counts once.
        entry: the node that is triggered exactly once at the start.
    
        The result has one key for every node that appears in `edges`, plus `entry`.
        Nodes that cannot be reached from `entry` are never triggered and map to 0.
        Raises ValueError if a cycle can be reached from `entry`.
        """
        # Phase 1: build deduplicated adjacency lists and find the subgraph reachable from entry.
        children = build_children(edges)
        if entry not in children:
            children[entry] = []
        reached = reachable_from(children, entry)
    
        # Phase 2: compute indegree[v] = number of REACHABLE parents of v.
        # Unreachable parents (like X -> D or Z -> entry) never fire, so v must not wait for them.
        indegree: Dict[Hashable, int] = {}
        for u in reached:
            indegree[u] = 0
        for u in reached:
            for v in children[u]:
                indegree[v] += 1
    
        # counts: maps every known node -> total times triggered; unreachable nodes stay 0.
        counts: Dict[Hashable, int] = {}
        for node in children:
            counts[node] = 0
        counts[entry] = 1
    
        # Phase 3: Kahn's topological sweep over the reachable subgraph.
        # In a DAG, entry is the unique reachable node with 0 reachable parents (unless on a cycle).
        queue: deque = deque()
        for u in reached:
            if indegree[u] == 0:
                queue.append(u)
    
        processed = 0
        while queue:
            u = queue.popleft()
            processed += 1
            # Every reachable parent of u has already been popped, so counts[u] is final.
            for v in children[u]:
                counts[v] += counts[u]
                indegree[v] -= 1
                if indegree[v] == 0:
                    queue.append(v)
    
        # If any reachable node never reached indegree 0, a cycle is reachable from entry.
        if processed != len(reached):
            raise ValueError("a cycle is reachable from the entry node")
    
        return counts
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture water flowing downhill through a network of one-way pipes (a directed acyclic graph, or DAG, meaning a graph of directed arrows with no loops): 1 gallon enters at entry, every splitter sends an equal copy down each outgoing pipe, and every junction adds together the water arriving from all of its incoming pipes. As long as you wait to read a junction's meter until every pipe feeding into it has finished, you can pass one combined total forward along each pipe instead of tracking millions of individual drops.

Simulating every trigger event one at a time fails because a chain of k diamond shapes doubles the number of triggers at every diamond (2^k events), turning 100,000 edges into more than 2^25000 operations. A standard breadth-first search with a visited set also fails: visiting a node once only records whether it is reachable (1 or 0), whereas forwarding a node's count before all its parents finish sends an incomplete sum downstream. Instead, we process reachable nodes in topological order (a sequence where every parent appears before all of its children) using Kahn's algorithm, which tracks each node's in-degree (the number of reachable incoming edges not yet processed) and enqueues a node only when its in-degree hits 0.

Walk through the 5-node workflow ingest -> parse, ingest -> audit, parse -> enrich, audit -> enrich, enrich -> notify, parse -> notify with entry = "ingest": 1. All five nodes are reachable from "ingest", with initial counts {ingest: 1, parse: 0, audit: 0, enrich: 0, notify: 0} and reachable in-degrees {ingest: 0, parse: 1, audit: 1, enrich: 2, notify: 2}, so the queue starts with [ingest]. 2. Pop ingest (1): both parse and audit get +1 and hit indegree == 0, entering the queue; pop parse (1): enrich and notify each get +1 (indegree 2 -> 1, so both wait). 3. Pop audit (1): enrich reaches 1 + 1 = 2 (indegree 1 -> 0, enqueue enrich), then pop enrich (2) to add 2 to notify (1 + 2 = 3, indegree 1 -> 0), finishing with 5 processed nodes and {ingest: 1, parse: 1, audit: 1, enrich: 2, notify: 3}.

Complexity

Let V be the number of distinct nodes (entry plus all nodes in edges) and E be the number of input edge pairs.

  • Time — O(V + E) graph operations (plus big-integer addition cost if counts grow exponentially): Building children and deduplicating edges scans the E pairs once with O(1) hash-set lookups; the iterative reachability DFS pushes and pops each reachable node at most once and crosses each deduplicated edge at most once; computing indegree and running Kahn's queue sweep again touches each reachable node and edge once. Note that Python integers have arbitrary precision: if k chained diamonds produce b-bit counts (b up to O(V)), adding two b-bit numbers takes O(b) bit operations, though for normal 64-bit counts each addition is O(1).
  • Space — O(V + E): children and seen_edges store at most V keys and E distinct edges, while reached, indegree, counts, the DFS stack, and Kahn's queue each hold at most V entries.

Edge cases

  • Empty edges list: count_triggers([], "A") returns {"A": 1}.
  • entry absent from edges: count_triggers([("B", "C")], "A") returns {"A": 1, "B": 0, "C": 0}.
  • Unreachable parent of a reachable node (or of entry): In Z -> A -> B -> D <- X, neither Z nor X is in reached, so indegree ignores both Z -> A and X -> D, allowing A and D to reach indegree == 0 normally while Z and X map to 0.
  • Duplicate edges in input: [("A", "B"), ("A", "B")] is deduplicated by seen_edges so B receives 1 trigger per firing of A (if a multigraph interpretation were requested instead, simply omit seen_edges).
  • Cycles — reachable vs. unreachable: A reachable cycle (A -> B -> C -> B, A -> B -> A, or self-loop B -> B) leaves cycle nodes with indegree > 0, so processed < len(reached) raises ValueError; an unreachable cycle (X <-> Y disconnected from A) never fires and cleanly maps to 0.
  • Deep chains of 100,000 nodes: Both reachable_from and Kahn's sweep are purely iterative, so Python never hits RecursionError.

Common mistakes

  • Simulating individual trigger events: Pushing a child onto a worklist every time it fires runs in O(total triggers) time instead of O(V + E), timing out on diamond chains.
  • Computing indegree over the entire graph instead of reached: If unreachable node X has an edge X -> D, indegree[D] starts 1 too high and never drops to 0, silently leaving all descendants of D at 0.
  • Enqueuing a child on the first parent visit instead of waiting for indegree == 0: Forwarding D's partial count before all parents of D have contributed undercounts every node downstream of D.
  • Writing recursive DFS or recursive memoization without raising the stack limit: On a 100,000-node linear chain, recursive traversal immediately exceeds Python's 1,000-frame call stack.
  • Using fixed 64-bit signed integers in C++/Java/Go without overflow checks: Just 63 diamonds reach 2^63, overflowing a signed 64-bit integer unless big integers, saturating arithmetic, or modular arithmetic is specified.

Alternative approaches

  • Iterative post-order DFS + reverse sweep: Running an iterative DFS from entry that records nodes on finish (while tracking on_stack nodes to catch cycle back-edges) produces a reverse topological order of reached; reversing that list and sweeping left-to-right propagates counts[v] += counts[u] in the same O(V + E) time without maintaining an indegree table.
  • Top-down memoized dynamic programming: Defining count(u) recursively as sum(count(v) ...) or over incoming parents caches one integer per node in O(V + E) time, though in Python it requires manual stack simulation to handle depth 100,000.

Follow-up questions

  • How would the algorithm change if several starting nodes fired with custom initial counts? Because trigger propagation is linear, initialize counts[node] from the initial-triggers dictionary (defaulting other nodes to 0), compute reached by seeding the iterative DFS stack with all entry nodes that have positive initial counts, and compute indegree over reached as before. Even if one entry node u can reach another entry node v (u -> v), v starts at its own initial count (say 5) and receives +counts[u] (say +3) when u is processed, yielding 8 in a single O(V + E) pass!
  • If cycles were permitted and cycling nodes should map to positive infinity, how would you compute the result? Decompose the reachable subgraph into strongly connected components, or SCCs (maximal groups of nodes where every node in the group can reach every other node in the group) in O(V + E) time using Tarjan's or Kosaraju's algorithm. Any reachable SCC with at least 2 nodes — or 1 node with a self-loop — triggers infinitely often, and every node reachable from such an SCC also receives float("inf"); the remaining finite nodes form a DAG whose exact integer counts come from our standard Kahn sweep.
  • How would you accelerate 50,000 repeated trigger-count queries against one fixed graph? Re-running an O(V + E) sweep 50,000 times takes roughly 5 * 10^9 operations, which is slow. If all queries ask about a small set of target sinks, run the DP once in reverse from each sink (paths_to_sink[u] = sum(paths_to_sink[v])) so any (entry, sink) query answers in O(1) dictionary lookup; if queries return full dictionaries, precompute one topological order of the entire DAG once so each query only sweeps from pos[entry] onward and skips zero-count nodes.

Follow-up questions

Similar questions

More Robinhood interview questions

All 60 Robinhood questions →