Compute Direct and Total Network Reach for Each User
Trees & GraphsModel answerLast updated
Given a list of sponsor–member pairs, return the direct and full downstream unique reach count for every user, handling duplicates, converging paths, and cycles.
Background
A peer-to-peer network tracks how members join through existing users. Each join event is recorded as a (sponsor, member) pair meaning sponsor brought member into the network. Your task is to analyze the influence reach of every user in this dataset.
For each user, compute two numbers:
- Direct count: how many unique people this user personally sponsored.
- Network count: how many unique people are reachable from this user through one or more sponsorship steps, not counting the user themselves.
The data is messy. You must handle all of the following:
- The same pair can appear more than once (duplicate records).
- A single person can be sponsored by multiple users (converging paths).
- Sponsorship chains can loop back on themselves (cycles).
- A user must never be counted in their own reach, even if a cycle connects back to them.
- Every user who appears in any position — sponsor or member — must have an entry in the output.
Function Signature
from typing import List, Tuple, Dict
def compute_reach(pairs: List[Tuple[str, str]]) -> Dict[str, Dict[str, int]]:
pass
Input & Output
- Input:
pairs— a list of(sponsor, member)tuples where each value is a non-empty alphanumeric string representing a user ID. - Output: a dictionary mapping each user ID to
{"direct": int, "network": int}.
Constraints
0 <= len(pairs) <= 5,000- Number of unique users
N <= 1,000 - User IDs are non-empty alphanumeric strings.
Examples
Example 1 — Converging paths
pairs = [
("A", "B"),
("A", "C"),
("B", "D"),
("C", "D"),
]
compute_reach(pairs)
# {
# "A": {"direct": 2, "network": 3}, # reaches B, C, D
# "B": {"direct": 1, "network": 1}, # reaches D
# "C": {"direct": 1, "network": 1}, # reaches D
# "D": {"direct": 0, "network": 0},
# }
Note that D is reachable from A via two paths but is counted only once.
Example 2 — Cycles and duplicates
pairs = [
("A", "B"),
("B", "C"),
("C", "A"),
("A", "B"), # duplicate
("C", "D"),
]
compute_reach(pairs)
# {
# "A": {"direct": 1, "network": 3}, # reaches B, C, D (not itself)
# "B": {"direct": 1, "network": 3}, # reaches C, D, A (not itself)
# "C": {"direct": 2, "network": 3}, # reaches A, B, D (not itself)
# "D": {"direct": 0, "network": 0},
# }
Edge Cases to Consider
- Empty input → return
{}. - A self-sponsorship like
("A", "A")→Agetsdirect: 0, network: 0(unless other edges exist). - Users who only appear as members (never as a sponsor) still get an entry with zero counts.
- Disconnected subgraphs.
Hints
Hint 1
Model the pairs as a directed graph. Direct count is simply the out-degree of each node once you've stripped duplicates and self-loops. What data structure removes duplicates automatically?
Hint 2
For network count, think about what 'all reachable nodes' means on a graph that may have cycles. A per-source BFS or DFS with a visited set gives you exactly the reachable set — how do you make sure the source node itself is never counted, even when a cycle circles back to it?
Hint 3
Summing children's network counts is tempting but wrong: if two paths converge on the same node it gets counted twice. The visited-set approach sidesteps this entirely. Once you have the visited set after BFS, the network count is just its size minus one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The pairs describe a directed graph: users are nodes and each unique (sponsor, member) pair is a directed edge. Two quantities follow directly from that model:
- Direct count = out-degree of a node after removing duplicate edges and self-loops.
- Network count = size of the reachable set from that node, minus the node itself.
The tricky part is network count. A naive approach — network(u) = Σ (1 + network(v)) over each child v — fails in two ways: converging paths cause double-counting (Example 1, D is counted once through B and once through C), and cycles cause infinite recursion. The fix is to treat it as a graph reachability problem rather than a tree aggregation.
Algorithm
- Scan every pair to collect all user IDs and build an adjacency list of sets (not lists). Using sets deduplicates edges automatically and skips self-loops cheaply.
- For each user
s, run a BFS seeded with{s}already in the visited set. Starting withsinvisitedmeans any cycle that leads back tossimply finds it already marked and stops — no special cycle detection needed. - After BFS:
network = len(visited) - 1,direct = len(adj[s]).
Why each anomaly is handled
| Anomaly | How it's handled |
|---|---|
| Duplicate pairs | Adjacency sets store each edge once |
| Self-sponsorship | Skipped when building edges; the node is still registered |
| Converging paths | Visited set counts each reachable node exactly once |
| Cycles | BFS never re-visits a node; seeding s blocks it from being counted |
| Members with no outgoing edges | Registered as nodes with empty adjacency sets; output is {direct:0, network:0} |
Complexity
Let N = unique users, E = unique edges.
- Building the graph: O(E)
- BFS per node: O(N + E); running it for all N nodes gives O(N · (N + E)) total
- Space: O(N + E) for the graph, O(N) for each BFS's visited set
At the stated limits (N = 1,000, E ≤ 5,000) this is roughly 6 million operations — well within any reasonable time budget.
Common mistakes
- Summing child network counts: produces wrong answers on any DAG with a shared descendant, and infinite loops on cycles.
- Forgetting to seed visited with the start node: the source gets incorrectly added to its own network count when a cycle wraps back to it.
- Using a list for adjacency: duplicates inflate the direct count.
- Omitting pure members from the output: any ID appearing only in the second column still needs an entry.
Solution
from typing import List, Tuple, Dict
from collections import deque
def compute_reach(pairs: List[Tuple[str, str]]) -> Dict[str, Dict[str, int]]:
# Build a deduplicated directed adjacency structure.
# Every user ID seen in either column gets an entry.
adj: Dict[str, set] = {}
for sponsor, member in pairs:
adj.setdefault(sponsor, set())
adj.setdefault(member, set())
if sponsor != member: # drop self-sponsorships
adj[sponsor].add(member)
result: Dict[str, Dict[str, int]] = {}
for start in adj:
# Seed visited with start so it is excluded from its own count,
# and so any cycle back to start terminates naturally.
visited = {start}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in adj[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
result[start] = {
"direct": len(adj[start]),
"network": len(visited) - 1, # subtract the start node itself
}
return result
DFS with an explicit stack is equally valid. Avoid recursive DFS in Python — a long sponsorship chain can easily hit the default recursion limit.
Tracing Example 2
After deduplication the edges are A→B, B→C, C→A, C→D.
- BFS from A: visits
A, B, C, D→ network = 3, direct = 1 ({B}) - BFS from C: visits
C, A, D, B→ network = 3, direct = 2 ({A, D})
Both match the expected output.
Follow-ups worth knowing
Graph is a guaranteed DAG. Converging paths still make summing children wrong. Instead, process nodes in reverse topological order and union descendant sets. With a bitset representation (Python int as a bitmask), each union is O(N/64), giving O(E · N/64) total — a meaningful speedup for dense DAGs.
For general graphs with cycles, first condense SCCs (Tarjan's or Kosaraju's algorithm), run the bitset DP on the condensed DAG, then distribute counts back: every node in an SCC of size k shares the same external reachable set and gets k − 1 added for its co-members.
Millions of users. Exact transitive closure scales as O(N²) and becomes impractical. Two practical alternatives:
- Approximate: attach a HyperLogLog sketch to each node and propagate sketches backward through edges iteratively (the HyperANF approach). HLL union is idempotent, so cycles and converging paths are handled automatically. Error is roughly 1–2% with a few KB per node.
- Bounded exact: if only k-hop reach matters (e.g., three levels of sponsorship), run k iterative graph expansion steps, which is much cheaper than full reachability.