Coding questions · Robinhood
Compute trigger counts in a DAG
This question evaluates understanding of directed acyclic graphs, graph traversal and accumulation of values across dependency edges, as well as algorithmic efficiency for handling large sparse graphs.
You are given a directed acyclic graph (DAG) that represents trigger dependencies between tasks.
- Each node represents a task.
- There is exactly one entry node.
- When a node is triggered once, it immediately triggers each of its outgoing neighbors once.
- A node may have multiple incoming edges; its total trigger count is the sum of triggers from all its parents.
- The entry node is triggered exactly once initially.
Your job is to compute how many times each node is triggered.
Input
- A list of directed edges
edges, where each edge is a pair(u, v)meaning there is an edgeu -> v. - A designated
entrynode ID. - You may assume:
- The graph is acyclic.
- All nodes that appear in
edgesare valid nodes. - Node IDs can be strings or integers (you can pick a representation and document it).
Example:
- Nodes:
A, B, C, D, E, F - Edges:
A -> BB -> CB -> DC -> DD -> ED -> FE -> F
- Entry node:
A
Trigger propagation:
Ais triggered once (given).Bis triggered once (fromA).Cis triggered once (fromB).Dis triggered twice (once fromB, once fromC).Eis triggered twice (both fromD).Fis triggered four times (twice fromD, twice fromE).
So the result is something equivalent to:
A: 1
B: 1
C: 1
D: 2
E: 2
F: 4
Task
Implement a function in Python with a signature such as:
def count_triggers(edges, entry):
"""Return a mapping from node to its trigger count."""
The function should:
- Validate that all reachable nodes from
entryare handled. - Run efficiently for graphs with up to around 10^5 nodes and 10^5 edges.
You may assume there are no cycles in the input graph.
Compute Trigger Counts in a DAG
Constraints
- 0 <= len(edges) <= 10^5
- The graph is acyclic
- Node IDs are strings or integers
- Only nodes reachable from entry should be included in the result
- The solution should run in O(V + E) time, where V is the number of nodes and E is the number of edges
Hints
- The trigger count of a node is the sum of the trigger counts of its parents. In a DAG, this is equivalent to counting paths from the entry node.
- Process only the reachable part of the graph in topological order so every parent contributes before its child is finalized.