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 either u or v is not present in nodes. Unlisted identifiers must never act as intermediate bridges connecting two members in nodes.
  • 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 edges and 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 nodes is non-empty and unique (case-sensitive).
  • 0 <= len(edges) <= 10,000, and every element of edges has length 2.
  • All kept edges between members of nodes form a directed acyclic graph (DAG).

Step-by-step walkthrough

  1. Restate the rules and visualize the DAG

    Let's pin down every rule from the specification:

    • Input: nodes has up to 2,000 unique, case-sensitive strings; edges has up to 10,000 directed pairs [u, v] (u -> v, meaning v and everything downstream of v count toward u).
    • Unlisted endpoints: If either u or v is missing from nodes, discard the edge completely. Unlisted names must never act as bridges between members in nodes.
    • 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)
    
  2. 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 4
    

    One valid way to avoid double-counting is to run a separate BFS or DFS starting from each of the n nodes (O(n * (n + m)) time, at most 2000 * 12000 ≈ 2.4 * 10^7 steps). 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.

  3. Represent reachable sets compactly as integer bitmasks

    How should we store reach(u) for up to 2,000 nodes?

    • Python set of ints: Simple, but memory-heavy and slow to copy. On a 2,000-node chain 0 -> 1 -> ... -> 1999, the 2,000 sets store roughly 2,000 * 1,000 / 2 ≈ 1,000,000 to 2,000,000 hash-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 bit j (1 << j) is 1 if node j is in the set, and 0 otherwise!

    Watch how bitwise OR (|) merges {noah, ava, leo} and {liam, ava, leo} in one instruction without ever double-counting ava or leo:

    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               = 4
    

    Because 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!

  4. Build the cleaned graph (dropping unlisted and duplicate edges)

    First, map each string in nodes to its integer index 0 .. n-1 (preserving exact case so "dev" and "Dev" stay distinct). Then scan edges:

    • 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_edges so 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
    
  5. Sort topologically with Kahn's algorithm

    To compute reach[u] from its children v, every child v must already have its final reach[v] mask ready.

    A topological order lists every parent u before every child v it points to (u -> v). Therefore, reading a topological order backwards (reversed(order)) visits every child v before all of its parents u!

    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 explicit deque instead 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 order
    
  6. Propagate bitmasks backwards and trace Example 1

    Walking u in reversed(order), each child v contributes (1 << v) | reach[v]. Because the graph is a DAG, u can never reach u, so bit u stays 0 automatically. 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]
    
  7. 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):

  1. Reverse topological order visits ava, then noah and liam, then mia.
  2. ava has no outgoing edges, so reach[ava] = 0b0000 (count 0).
  3. noah points to ava(0): reach[noah] = (1 << 0) | 0b0000 = 0b0001 (count 1). Likewise reach[liam] = 0b0001 (count 1).
  4. mia points to noah(1) and liam(2): reach[mia] = ((1 << 1) | 0b0001) | ((1 << 2) | 0b0001) = 0b0011 | 0b0101 = 0b0111 ({ava, noah, liam}, count 3 — ava's bit 0 was 1 | 1 = 1, never 2).

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 the n node names, filtering/deduplicating the m edges, 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 most m kept edges performs one bitwise OR on n-bit integers, costing O(n / w) limb operations per edge (10,000 * 67 ≈ 6.7 * 10^5 fast C loop steps at maximum constraints). Finally, bin(mask).count("1") scans an O(n)-character binary string for each of the n nodes (O(n^2), at most 4 * 10^6 C-level byte checks).
  • Space: O(n^2 / w + n + m). Storing n integer bitmasks of up to n bits uses n^2 / w limbs — well under 1 MB at n = 2000 — plus O(n + m) space for name_to_idx, seen_edges, children, and indegree.

Edge cases

  • Empty nodes (nodes = []): every edge (if any) fails the name_to_idx check, returning [].
  • Isolated nodes and sinks (zero outgoing edges): reach[u] stays 0, yielding count 0.
  • Unlisted endpoints (["zoe", "ext"], ["ext", "leo"]): both edges are discarded before building children, so "ext" cannot create an artificial bridge from "zoe" to "leo".
  • Duplicate edges (["mia", "noah"] repeated multiple times): seen_edges keeps 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 in name_to_idx without .lower() or .upper().
  • 2,000-node linear chain: iterative deque in Kahn's algorithm avoids Python's 1,000-frame recursion limit.
  • Edge direction convention: [u, v] follows u -> v (v counts toward u); 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 (6 instead of 4 for "mia" in Example 1).
  • Auto-inserting unlisted node names into the graph: adding "ext" as a temporary node creates a path zoe -> ext -> leo that connects "zoe" to "leo" even if "ext" is filtered out at the end.
  • Forgetting (1 << v) in mask |= (1 << v) | reach[v]: writing mask |= reach[v] alone copies v's descendants without ever adding v itself, leaving every node with count 0!
  • Iterating order forward instead of reversed(order): parents then read reach[v] == 0 before their children have been computed.
  • Using recursive DFS on n = 2000 without sys.setrecursionlimit: crashes with RecursionError on a deep path.
  • Sharing a single visited set 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 one visited set at a time) and works even if cycles exist, making it ideal when memory cannot hold n^2 bits, though it repeats work across shared subgraphs in Python.
  • Python set propagation: replaces integer bitmasks with set[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 in O(n + m) time using Tarjan's or Kosaraju's algorithm) into a single supernode; the graph of supernodes is guaranteed to be a DAG. Propagate n-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,000 bitmasks of 200,000 bits each would take 4 * 10^10 bits (~5 GB of RAM). Fix the memory blowup with chunked bitsets: partition the n target nodes into blocks of B = 65,536 nodes (8 KB per mask) and run the exact same reverse-topological pass ceil(n / B) times (4 passes), adding bit_count(reach[u]) from each block into counts[u] — keeping peak bitset memory around 1.6 GB (or 200 MB with B = 8,192) with the exact same total CPU work. If 1–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-wise max of registers) in a single O(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 -> v arrives (assuming it does not create a cycle), u and every ancestor that can reach u gain added = (1 << v) | reach[v]. Walk backward along reverse edges from u, updating reach[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 collect u and its ancestors and recompute their masks from their children in reverse topological order.

Follow-up questions

Similar questions

More Robinhood interview questions

All 60 Robinhood questions →