Distinct Downstream Reachability in a Referral DAG
Hard · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given a roster of member identifiers nodes and a list of one-way referral links edges. Each element [u, v] in edges denotes a directed link u -> v (member u directly referred member v), meaning v—along with every member reachable further downstream from v—counts toward u's downstream network, whereas u does not count toward v.
Implement the function:
def referral_counts(nodes: List[str], edges: List[List[str]]) -> List[int]:
For each member nodes[i], compute how many distinct other members in nodes can be reached by following one or more valid directed edges starting at nodes[i], and return those counts as an integer list aligned with the order of nodes.
Apply these exact graph rules:
- Discard any edge
[u, v]where eitheruorvis not present innodes. Unlisted identifiers must never act as intermediate bridges connecting two members innodes. - After discarding edges with unlisted endpoints, the remaining directed graph is guaranteed to contain no cycles (it is a directed acyclic graph).
- Duplicate edges may appear in
edgesand must be treated identically to a single edge. - Member identifiers are case-sensitive (
"dev"and"Dev"are distinct). - Do not count a member toward its own total, and count shared downstream members reached along multiple converging paths only once. Members with no valid outgoing edges have count
0.
Examples
Example 1
Input:
nodes = ["mia", "noah", "liam", "ava", "leo", "zoe"]
edges = [
["mia", "noah"],
["mia", "liam"],
["noah", "ava"],
["liam", "ava"],
["ava", "leo"],
["mia", "noah"],
["zoe", "ext"],
["ext", "leo"]
]
Output: [4, 2, 2, 1, 0, 0]
Explanation: Because "ext" is absent from nodes, both ["zoe", "ext"] and ["ext", "leo"] are dropped, leaving "zoe" isolated with count 0 (and preventing an indirect path from "zoe" to "leo"). The duplicate ["mia", "noah"] edge is ignored. "ava" reaches {"leo"} (1), "noah" and "liam" each reach {"ava", "leo"} (2), and "mia" reaches {"noah", "liam", "ava", "leo"} (4—shared nodes "ava" and "leo" are counted once even though two paths from "mia" reconverge at "ava").
Example 2
Input:
nodes = ["dev", "ops", "Dev", "qa"]
edges = [["Dev", "ops"], ["ops", "qa"], ["dev", "OPS"]]
Output: [0, 1, 2, 0]
Explanation: Identifiers are case-sensitive: "OPS" is not in nodes, so ["dev", "OPS"] is discarded and "dev" reaches 0 members. Following "Dev" -> "ops" -> "qa", "ops" reaches {"qa"} (1), "Dev" reaches {"ops", "qa"} (2), and "qa" reaches {} (0).
Constraints
0 <= len(nodes) <= 2,000- Every string in
nodesis non-empty and unique (case-sensitive). 0 <= len(edges) <= 10,000, and every element ofedgeshas length2.- All kept edges between members of
nodesform a directed acyclic graph (DAG).
Step-by-step walkthrough
Restate the rules and visualize the DAG
Let's pin down every rule from the specification:
- Input:
nodeshas up to2,000unique, case-sensitive strings;edgeshas up to10,000directed pairs[u, v](u -> v, meaningvand everything downstream ofvcount towardu). - Unlisted endpoints: If either
uorvis missing fromnodes, discard the edge completely. Unlisted names must never act as bridges between members innodes. - DAG & duplicates: Remaining edges form a directed acyclic graph (DAG) — a one-way network with no cycles. Duplicate edges may appear and must not inflate counts.
- Output: A list of integers parallel to
nodes, giving the number of distinct reachable downstream nodes (excluding the node itself) for each node.
Here is Example 1 after discarding
["zoe", "ext"],["ext", "leo"], and the duplicate["mia", "noah"]:mia / \ zoe (isolated once "ext" edges are dropped) v v noah liam \ / v v ava | v leo Reachable sets: mia -> {noah, liam, ava, leo} (4) noah -> {ava, leo} (2) liam -> {ava, leo} (2) ava -> {leo} (1) leo -> {} (0) zoe -> {} (0)- Input:
Why adding child counts fails when paths merge
In a tree, you can compute a parent's descendant count by summing
1 + count(child)across its children. In a general DAG, paths can split and merge back together, and plain numbers lose track of which nodes overlapped!Look at
"mia"in the diamond above:Wrong (summing child counts): via noah: 1 + count(noah) = 1 + 2 = 3 (counts noah, ava, leo) via liam: 1 + count(liam) = 1 + 2 = 3 (counts liam, plus ava and leo AGAIN!) total = 3 + 3 = 6 <-- WRONG: ava and leo were counted twice! Right (unioning reachable sets): reach(mia) = ({noah} ∪ reach(noah)) ∪ ({liam} ∪ reach(liam)) = {noah, ava, leo} ∪ {liam, ava, leo} = {noah, liam, ava, leo} --> size 4One valid way to avoid double-counting is to run a separate BFS or DFS starting from each of the
nnodes (O(n * (n + m))time, at most2000 * 12000 ≈ 2.4 * 10^7steps). That works as a brute-force reference, but every search re-walks shared subgraphs from scratch. Instead, we can compute each node's reachable set once and combine child sets upward using set union.Represent reachable sets compactly as integer bitmasks
How should we store
reach(u)for up to2,000nodes?- Python
setof ints: Simple, but memory-heavy and slow to copy. On a 2,000-node chain0 -> 1 -> ... -> 1999, the 2,000 sets store roughly2,000 * 1,000 / 2 ≈ 1,000,000to2,000,000hash-table slots (around 80–90 MB in CPython). - Integer bitmask (bitset): Assign each node an index
0 .. n-1. Represent a set of nodes as a single Python integer whose binary bitj(1 << j) is1if nodejis in the set, and0otherwise!
Watch how bitwise OR (
|) merges{noah, ava, leo}and{liam, ava, leo}in one instruction without ever double-countingavaorleo:Node indices: zoe=5, leo=4, ava=3, liam=2, noah=1, mia=0 (bits written 5 4 3 2 1 0) {noah} ∪ reach(noah) = (1 << 1) | 0b011000 = 0b011010 ({leo, ava, noah}) {liam} ∪ reach(liam) = (1 << 2) | 0b011000 = 0b011100 ({leo, ava, liam}) -------- reach(mia) = 0b011010 | 0b011100 = 0b011110 ({leo, ava, liam, noah}) number of 1-bits in 0b011110 = 4Because Python
ints have arbitrary precision, one 2,000-bit integer takes under 300 bytes in CPython — so all 2,000 masks together fit in under 1 MB, and each union combines 30–64 bits per CPU step!- Python
Build the cleaned graph (dropping unlisted and duplicate edges)
First, map each string in
nodesto its integer index0 .. n-1(preserving exact case so"dev"and"Dev"stay distinct). Then scanedges:- If either endpoint is not in
name_to_idx, skip the edge immediately. That guarantees"ext"never enters the graph and never links"zoe"to"leo". - Track
seen_edgesso duplicate edges like["mia", "noah"]repeated twice are stored only once.
def build_children(nodes: List[str], edges: List[List[str]]) -> List[List[int]]: """Build deduplicated adjacency lists over 0..len(nodes)-1, dropping unknown endpoints.""" # name_to_idx: {node_name: int_id}, e.g. {"mia": 0, "noah": 1}; case-sensitive lookup. name_to_idx: Dict[str, int] = {} for idx, name in enumerate(nodes): name_to_idx[name] = idx # children[u]: unique node indices v with a valid directed edge u -> v. children: List[List[int]] = [[] for _ in nodes] seen_edges: Set[Tuple[int, int]] = set() for source_name, target_name in edges: # Discard the entire edge if either endpoint is missing from nodes so an # unlisted identifier like "ext" can never bridge two known nodes. if source_name not in name_to_idx or target_name not in name_to_idx: continue pair = (name_to_idx[source_name], name_to_idx[target_name]) if pair in seen_edges: continue seen_edges.add(pair) children[pair[0]].append(pair[1]) return children- If either endpoint is not in
Sort topologically with Kahn's algorithm
To compute
reach[u]from its childrenv, every childvmust already have its finalreach[v]mask ready.A topological order lists every parent
ubefore every childvit points to (u -> v). Therefore, reading a topological order backwards (reversed(order)) visits every childvbefore all of its parentsu!We compute the topological order iteratively with Kahn's algorithm (counting incoming edges in
indegree, starting a queue with all zero-indegree nodes, and peeling off edges one by one). Using an explicitdequeinstead of recursive DFS avoids hitting Python's default 1,000-call recursion limit when the DAG is a 2,000-node chain.def topological_order(children: List[List[int]]) -> List[int]: """Return nodes in topological order (every parent before its children) via Kahn's BFS.""" num_nodes = len(children) # indegree[v]: number of remaining incoming edges into node v. indegree = [0] * num_nodes for u in range(num_nodes): for v in children[u]: indegree[v] += 1 # Iterative queue avoids Python's 1000-frame recursion limit on 2000-node chains. ready = deque(u for u in range(num_nodes) if indegree[u] == 0) order: List[int] = [] while ready: u = ready.popleft() order.append(u) for v in children[u]: indegree[v] -= 1 if indegree[v] == 0: ready.append(v) if len(order) != num_nodes: raise ValueError("the edges between known nodes contain a cycle") return orderPropagate bitmasks backwards and trace Example 1
Walking
uinreversed(order), each childvcontributes(1 << v) | reach[v]. Because the graph is a DAG,ucan never reachu, so bitustays0automatically. Finally,bin(mask).count("1")counts the set bits on every Python 3 version.Let's trace Example 1 (
mia=0, noah=1, liam=2, ava=3, leo=4, zoe=5):Kahn's topological order: [mia(0), zoe(5), noah(1), liam(2), ava(3), leo(4)] Reversed order: [leo(4), ava(3), liam(2), noah(1), zoe(5), mia(0)] Step Node Children Bitmask calculation Mask (bits 5..0) Count ------------------------------------------------------------------------------------------- 1 leo(4) [] 0 0b000000 0 2 ava(3) [leo(4)] (1 << 4) | reach[4] = 0b010000 | 0 0b010000 1 3 liam(2) [ava(3)] (1 << 3) | reach[3] = 0b001000 | 0b010000 0b011000 2 4 noah(1) [ava(3)] (1 << 3) | reach[3] = 0b001000 | 0b010000 0b011000 2 5 zoe(5) [] 0 0b000000 0 6 mia(0) [noah(1), ((1 << 1) | 0b011000) | 0b011110 4 liam(2)] ((1 << 2) | 0b011000) = 0b011010 | 0b011100 Counts in original node order [mia, noah, liam, ava, leo, zoe]: [4, 2, 2, 1, 0, 0]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def build_children(nodes: List[str], edges: List[List[str]]) -> List[List[int]]: """Build deduplicated adjacency lists over 0..len(nodes)-1, dropping unknown endpoints.""" # name_to_idx: {node_name: int_id}, e.g. {"mia": 0, "noah": 1}; case-sensitive lookup. name_to_idx: Dict[str, int] = {} for idx, name in enumerate(nodes): name_to_idx[name] = idx # children[u]: unique node indices v with a valid directed edge u -> v. children: List[List[int]] = [[] for _ in nodes] seen_edges: Set[Tuple[int, int]] = set() for source_name, target_name in edges: # Discard the entire edge if either endpoint is missing from nodes so an # unlisted identifier like "ext" can never bridge two known nodes. if source_name not in name_to_idx or target_name not in name_to_idx: continue pair = (name_to_idx[source_name], name_to_idx[target_name]) if pair in seen_edges: continue seen_edges.add(pair) children[pair[0]].append(pair[1]) return children def topological_order(children: List[List[int]]) -> List[int]: """Return nodes in topological order (every parent before its children) via Kahn's BFS.""" num_nodes = len(children) # indegree[v]: number of remaining incoming edges into node v. indegree = [0] * num_nodes for u in range(num_nodes): for v in children[u]: indegree[v] += 1 # Iterative queue avoids Python's 1000-frame recursion limit on 2000-node chains. ready = deque(u for u in range(num_nodes) if indegree[u] == 0) order: List[int] = [] while ready: u = ready.popleft() order.append(u) for v in children[u]: indegree[v] -= 1 if indegree[v] == 0: ready.append(v) if len(order) != num_nodes: raise ValueError("the edges between known nodes contain a cycle") return order def referral_counts(nodes: List[str], edges: List[List[str]]) -> List[int]: # Phase 1: Map names to 0..n-1, filter unknown endpoints, and sort topologically. children = build_children(nodes, edges) order = topological_order(children) # Phase 2: Propagate reachability bitmasks in REVERSE topological order so every # child v is completely computed before any parent u unions reach[v]. # reach[u]: integer bitmask where bit v ((reach[u] >> v) & 1) is 1 iff u reaches v. reach = [0] * len(nodes) for u in reversed(order): mask = 0 for v in children[u]: # Include bit v itself (1 << v) plus every node reachable downstream of v. mask |= (1 << v) | reach[v] reach[u] = mask # Phase 3: Count the 1-bits in each node's mask (u's own bit is never set in a DAG). counts: List[int] = [] for mask in reach: counts.append(bin(mask).count("1")) return counts✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tracking an employee referral network to count how many unique people sit downstream of each employee, where two colleagues might both connect to the same downstream person (a network of one-way arrows with no loops, called a directed acyclic graph (DAG)). If you ask your two direct referrals "how many people are downstream of you?" and simply add their numbers together, anyone downstream of both of them gets counted twice. To avoid double-counting, each person must pass up their set of reachable people, not just a headcount.
Running a separate graph search from every single node works (O(n * (n + m))), but wastes work re-exploring the same shared subgraphs over and over. On the other hand, propagating Python set objects upward copies millions of hash-table entries (~90 MB) on a 2,000-node chain.
We get the best of both worlds with an integer bitmask (a single integer whose binary digits act as a compact row of 0/1 checkboxes, where bit j is 1 when node j is reachable). First, we compute a topological order (a node ordering where every u appears before every v it points to) using Kahn's algorithm (an iterative queue-based peel of zero-incoming-edge nodes). Walking that order backwards guarantees every child v is finished before its parent u, so u merges each child's roster in one bitwise OR: mask |= (1 << v) | reach[v].
Here is a tiny 4-node diamond trace (mia -> noah -> ava and mia -> liam -> ava, with indices ava=0, noah=1, liam=2, mia=3):
- Reverse topological order visits
ava, thennoahandliam, thenmia. avahas no outgoing edges, soreach[ava] = 0b0000(count0).noahpoints toava(0):reach[noah] = (1 << 0) | 0b0000 = 0b0001(count1). Likewisereach[liam] = 0b0001(count1).miapoints tonoah(1)andliam(2):reach[mia] = ((1 << 1) | 0b0001) | ((1 << 2) | 0b0001) = 0b0011 | 0b0101 = 0b0111({ava, noah, liam}, count3—ava's bit0was1 | 1 = 1, never2).
Complexity
Let n be len(nodes) (n <= 2000), m be len(edges) (m <= 10000), and w be the integer word size (w = 30 bits per limb in CPython's arbitrary-precision integers, or 64 on raw hardware words).
- Time: O(n + m * n / w + n^2) (or O(n + m * n / w) using
int.bit_count()in Python 3.10+). Indexing thennode names, filtering/deduplicating themedges, and running Kahn's topological sort each touch every node and edge a constant number of times (O(n + m)). In the reverse pass, each of the at mostmkept edges performs one bitwise OR onn-bit integers, costingO(n / w)limb operations per edge (10,000 * 67 ≈ 6.7 * 10^5fast C loop steps at maximum constraints). Finally,bin(mask).count("1")scans anO(n)-character binary string for each of thennodes (O(n^2), at most4 * 10^6C-level byte checks). - Space: O(n^2 / w + n + m). Storing
ninteger bitmasks of up tonbits usesn^2 / wlimbs — well under1 MBatn = 2000— plusO(n + m)space forname_to_idx,seen_edges,children, andindegree.
Edge cases
- Empty
nodes(nodes = []): every edge (if any) fails thename_to_idxcheck, returning[]. - Isolated nodes and sinks (zero outgoing edges):
reach[u]stays0, yielding count0. - Unlisted endpoints (
["zoe", "ext"],["ext", "leo"]): both edges are discarded before buildingchildren, so"ext"cannot create an artificial bridge from"zoe"to"leo". - Duplicate edges (
["mia", "noah"]repeated multiple times):seen_edgeskeeps one copy, and bitwise OR (x | x == x) is naturally idempotent anyway. - Diamond / reconverging paths: shared descendants map to the same bit index and are counted once.
- Case-sensitive names (
"dev"vs"Dev"): stored as distinct keys inname_to_idxwithout.lower()or.upper(). - 2,000-node linear chain: iterative
dequein Kahn's algorithm avoids Python's 1,000-frame recursion limit. - Edge direction convention:
[u, v]followsu -> v(vcounts towardu); in a live interview, always confirm edge direction on a 3-node example before coding.
Common mistakes
- Summing
1 + count(v)across children: works only on trees and overcounts whenever two paths reconverge (6instead of4for"mia"in Example 1). - Auto-inserting unlisted node names into the graph: adding
"ext"as a temporary node creates a pathzoe -> ext -> leothat connects"zoe"to"leo"even if"ext"is filtered out at the end. - Forgetting
(1 << v)inmask |= (1 << v) | reach[v]: writingmask |= reach[v]alone copiesv's descendants without ever addingvitself, leaving every node with count0! - Iterating
orderforward instead ofreversed(order): parents then readreach[v] == 0before their children have been computed. - Using recursive DFS on
n = 2000withoutsys.setrecursionlimit: crashes withRecursionErroron a deep path. - Sharing a single
visitedset across starts in brute-force search: causes later nodes to skip subgraphs visited by earlier nodes.
Alternative approaches
Here is how the three exact approaches compare on n nodes and m edges:
Approach Time complexity Extra memory At n=2000, m=10000
----------------------------------------------------------------------------------------------
Separate BFS/DFS per node O(n * (n + m)) O(n + m) ~2.4e7 Python steps
Python set union (topo order) O(m * n) O(n^2) set entries ~80-90 MB RAM
Bitmask OR (topo order, ours) O(n + m*n/w + n^2) O(n^2 / w) words < 1 MB RAM, fastest
- Separate BFS/DFS from each node: minimal extra memory (
O(n)for onevisitedset at a time) and works even if cycles exist, making it ideal when memory cannot holdn^2bits, though it repeats work across shared subgraphs in Python. - Python
setpropagation: replaces integer bitmasks withset[int]unions in reverse topological order; conceptually identical to bitmasks, but hash-set overhead uses roughly 100x more memory and slower element-by-element copying.
Follow-up questions
- How would you modify your algorithm if the referral links were permitted to form directed cycles? In a graph with cycles, Kahn's algorithm stops early because nodes in a cycle never reach
indegree == 0. First collapse each strongly connected component (SCC) (a maximal group of nodes that can all reach one another, found inO(n + m)time using Tarjan's or Kosaraju's algorithm) into a single supernode; the graph of supernodes is guaranteed to be a DAG. Propagaten-bit masks in reverse topological order over the supernode DAG (initializing each supernode's mask with all its member bits), and mask out a node's own bit (comp_mask[S] & ~(1 << u)) before counting set bits so self-reachability through a cycle is excluded. - Suppose the network grows to 200,000 members and 1,000,000 links; how can you avoid running out of memory while keeping bitset speed? Storing
200,000bitmasks of200,000bits each would take4 * 10^10bits (~5 GBof RAM). Fix the memory blowup with chunked bitsets: partition thentarget nodes into blocks ofB = 65,536nodes (8 KBper mask) and run the exact same reverse-topological passceil(n / B)times (4passes), addingbit_count(reach[u])from each block intocounts[u]— keeping peak bitset memory around1.6 GB(or200 MBwithB = 8,192) with the exact same total CPU work. If1–2%approximate counts are acceptable, propagate a HyperLogLog sketch (a fixed-size probabilistic counter of ~1–3 KB per node whose union is an element-wisemaxof registers) in a singleO(m)pass. - If new referral edges arrive incrementally over time, how would you update affected counts without recomputing the entire graph? When a new valid edge
u -> varrives (assuming it does not create a cycle),uand every ancestor that can reachugainadded = (1 << v) | reach[v]. Walk backward along reverse edges fromu, updatingreach[x] |= added, and prune any branch as soon as(reach[x] | added) == reach[x]because nothing further upstream can gain new bits either. Edge deletions are trickier because an alternate path might still reach the same nodes, so you collectuand its ancestors and recompute their masks from their children in reverse topological order.
Follow-up questions
- How would you modify your algorithm if the referral links were permitted to form directed cycles?
- Suppose the network grows to 200,000 members and 1,000,000 links; how can you avoid running out of memory while keeping bitset speed?
- If new referral edges arrive incrementally over time, how would you update affected counts without recomputing the entire graph?
Similar questions
- Group Activity Logs into Inactivity-Bounded Sessions
- Weekly Calendar State and Derived Grid
- Cumulative Task Loads Across a DAG
- Downstream Traffic Multipliers in a Service Graph
- Room-to-Gate Shortest Distances on a Grid
- DAG Task Propagation Counts
More Robinhood interview questions
- Downstream Traffic Multipliers in a Service Graph Medium
- DAG Task Propagation Counts Easy
- Surfacing Technical Complexity and Scaling Trade-Offs on a Whiteboard Hard Pro
- Whole-Share Inventory Sweeping for Fractional Orders Medium Pro
- Weekly Calendar State and Derived Grid Medium Pro
- Justifying Technical Complexity and Scaling Trade-Offs Under Pushback Medium Pro
- Direct and Reachable Referral Graph Counts Medium Pro
- Fault-Tolerant Recurring Cron Scheduler at 100K Scale Medium Pro
- Strict At-Most-Once Background Task Scheduler Hard Pro
- Crash-Resilient Distributed Task Scheduler Medium Pro