Analyze Referral Chains and Detect Graph Cycles
Trees & GraphsModel answerLast updated
Process referral relationships with at most one parent per user. Detect cycles, extract acyclic prefixes, and compute root ancestors and depths for all users in O(n) total time.
You are given data representing a direct referral network where each user can be invited by at most one referrer (parent). The dataset comes as a CSV file (referrals.csv) with two columns: user_id (integer) and referred_by (integer, optional/nullable).
The system contains up to $10^6$ users. Real-world conditions introduce anomalies:
referred_bymay refer to auser_idthat does not exist in the file (treat as an external root).- Duplicate rows might exist with conflicting referrers.
- Self-referrals (e.g., $A \to A$) and multi-node referral cycles (e.g., $A \to B \to A$) may be present.
Write Python code to solve the following requirements:
-
Preprocessing & Robustness:
- Parse and deduplicate the input dataset. If duplicate entries exist for the same
user_id, keep the first non-null parent encountered. - Clean up missing/empty values for
referred_by. - Identify self-referrals and external referrers appropriately.
- Parse and deduplicate the input dataset. If duplicate entries exist for the same
-
Single User Path Traversal (
chain(u)):- Write a function
chain(u)that walks upstream fromuto its earliest reachable ancestor. - If the walk is acyclic, return the path starting at the root ancestor and ending at
u. - If a cycle is hit along the path, safely abort traversal without looping endlessly and return a tuple
(prefix, cycle)wherecycleis the list of nodes forming the cycle in encounter order, andprefixis the path of nodes leading into that cycle.
- Write a function
-
Global Network Traversal in $O(n)$ Time & Space:
- Compute
(root_ancestor[u], chain_depth[u])for every user in $O(n)$ total time and $O(n)$ space. chain_depth[u]is defined as the number of distinct referrers on the path from the root down tou(a node directly under a root has depth 1).- If a user lies within a cycle or leads into one (a cycle tail), assign
root_ancestor = Noneandchain_depth = None(or mark them as cyclic). - Avoid performing full $O(n)$ walks per node; use memoization, graph coloring, or iterative DFS.
- Compute
-
Top-3 Longest Acyclic Chains:
- Extract the top 3 longest maximal acyclic chains (paths from root to a leaf node).
- Tie-breaking rules:
- Primary: Larger path length (number of nodes).
- Secondary: Smaller
root_ancestorID. - Tertiary: Lexicographically smaller path array.
-
Unit Testing:
- Provide minimal executable unit tests covering:
- A standard linear acyclic chain.
- A single-node self-cycle.
- A multi-node cycle (e.g., 2 nodes).
- Provide minimal executable unit tests covering:
Sample Input (referrals.csv):
user_id,referred_by
1,
2,1
3,1
4,2
5,4
6,5
7,7
8,9
9,8
Hints
Hint 1
Since each user has at most one parent, every node in this graph has an out-degree of at most 1 (a functional graph). Components are strictly trees or cycles with attached trees.
Hint 2
To execute global computation in O(n) total time, use 3-color DFS marking (Unvisited, Visiting/On-Stack, Visited) or iterative memoization to avoid revisiting nodes.
Hint 3
When extracting top chains, ensure you only consider maximal paths (root-to-leaf) to prevent redundant sub-paths from filling the top results.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Structural Analysis
Because each user has at most one direct referrer (referred_by), this structure forms a functional graph (out-degree $\le 1$ when pointing from user to referrer). This property simplifies cycle detection and linear traversal:
- Tree Components: Paths terminate either at a root node (
referred_by is None) or at an external ID not defined as auser_idin the dataset. - Cycle Components: Paths eventually hit a node currently in the active traversal stack, forming a cycle of length $\ge 1$.
Key Requirements & Complexity Guarantees
- Preprocessing: We store relationships in a dictionary
parent_map: Dict[int, Optional[int]]. When duplicateuser_identries appear, the first non-null parent observed is retained. - Single Traversal (
chain(u)): We walk upwards fromu. Using a hash map ofvisited_index: Dict[int, int], we track the step index at which each node was visited. If we hit a node already present invisited_indexat stepi, the sequence up toiis theprefix, and fromionward is thecycle. - Global Evaluation ($O(n)$ total time): A naive approach calling
chain(u)for all $n$ nodes would take $O(n^2)$ worst-case time (e.g., a long linear chain). To achieve $O(n)$ overall time, we use standard 3-state DFS coloring:0 (UNVISITED)1 (VISITING / ON_STACK)2 (VISITED / PROCESSED)
When traversing during global analysis:
- If we land on a state
2node, we immediately inherit its memoized(root, depth)values. - If we land on a state
1node, we have detected a cycle on the current recursion stack and mark all nodes involved in the stack loop as cyclic (root = None, depth = None).
Python Implementation
from typing import Dict, List, Optional, Tuple, Set
class ReferralAnalyzer:
def __init__(self):
self.parent_map: Dict[int, Optional[int]] = {}
self.all_users: Set[int] = set()
def load_and_preprocess(self, rows: List[Tuple[str, str]]) -> None:
"""
Deduplicates rows, normalizes nulls, and handles missing/external parent IDs.
Rows format: (user_id_str, referred_by_str)
"""
for u_str, p_str in rows:
u_str = u_str.strip()
p_str = p_str.strip() if p_str else ""
if not u_str.isdigit():
continue # Skip header or malformed entries
u = int(u_str)
self.all_users.add(u)
p = int(p_str) if p_str.isdigit() else None
# First non-null parent takes precedence if duplicate user_id exists
if u not in self.parent_map:
self.parent_map[u] = p
elif self.parent_map[u] is None and p is not None:
self.parent_map[u] = p
def chain(self, u: int) -> Tuple[List[int], List[int]]:
"""
Walks up from user u.
Returns:
- (path_from_root_to_u, []) if acyclic.
- (prefix_path, cycle_nodes) if a cycle is encountered.
"""
visited = {}
path = []
curr = u
while curr is not None:
if curr in visited:
idx = visited[curr]
# path[:idx] is the path leading to the cycle
# path[idx:] is the cycle in order of encounter
prefix = path[:idx][::-1]
cycle = path[idx:][::-1]
return prefix, cycle
visited[curr] = len(path)
path.append(curr)
# Move to parent
curr = self.parent_map.get(curr)
# Reached a root or external node without cycle
# Output ordered from root to u
return path[::-1], []
def compute_all_metrics(self) -> Tuple[Dict[int, Optional[int]], Dict[int, Optional[int]]]:
"""
Computes root_ancestor and chain_depth for every node in O(N) time and space.
"""
root_map: Dict[int, Optional[int]] = {}
depth_map: Dict[int, Optional[int]] = {}
state: Dict[int, int] = {u: 0 for u in self.all_users} # 0: Unvisited, 1: Visiting, 2: Visited
def dfs(node: int) -> Tuple[Optional[int], Optional[int]]:
# External ID (not explicitly defined in file)
if node not in self.parent_map:
return node, 0
if state[node] == 2:
return root_map[node], depth_map[node]
if state[node] == 1:
# Cycle detected on active recursion stack
return None, None
state[node] = 1
parent = self.parent_map[node]
if parent is None:
# Node itself is a root
root, depth = node, 0
else:
p_root, p_depth = dfs(parent)
if p_root is None:
root, depth = None, None
else:
root, depth = p_root, p_depth + 1
root_map[node] = root
depth_map[node] = depth
state[node] = 2
return root, depth
for user in self.all_users:
if state[user] == 0:
dfs(user)
return root_map, depth_map
def get_top_3_chains(() -> List[List[int]]:
"""
Returns top-3 maximal acyclic chains sorted by:
1. Length (descending)
2. Root user ID (ascending)
3. Path elements lexicographically (ascending)
"""
# Identify children to find leaf nodes
parents_set = set(p for p in self.parent_map.values() if p is not None)
leaves = [u for u in self.all_users if u not in parents_set]
valid_chains = []
for leaf in leaves:
path, cycle = self.chain(leaf)
if not cycle and path:
valid_chains.append(path)
# Sort criteria: (-len, root_id, full_path)
valid_chains.sort(key=lambda p: (-len(p), p[0], p))
return valid_chains[:3]
Unit Tests
def test_referral_analyzer():
raw_csv_data = [
("user_id", "referred_by"),
("1", ""),
("2", "1"),
("3", "1"),
("4", "2"),
("5", "4"),
("6", "5"),
("7", "7"),
("8", "9"),
("9", "8"),
]
analyzer = ReferralAnalyzer()
analyzer.load_and_preprocess(raw_csv_data[1:])
# Test 1: Acyclic chain for user 6
path_6, cycle_6 = analyzer.chain(6)
assert path_6 == [1, 2, 4, 5, 6], f"Expected [1, 2, 4, 5, 6], got {path_6}"
assert cycle_6 == [], f"Expected empty cycle, got {cycle_6}"
# Test 2: Metrics computation for user 6
roots, depths = analyzer.compute_all_metrics()
assert roots[6] == 1, f"Expected root 1, got {roots[6]}"
assert depths[6] == 4, f"Expected depth 4, got {depths[6]}"
# Test 3: Self-cycle for user 7
path_7, cycle_7 = analyzer.chain(7)
assert cycle_7 == [7], f"Expected self-cycle [7], got {cycle_7}"
assert roots[7] is None
assert depths[7] is None
# Test 4: 2-node cycle for users 8 and 9
path_8, cycle_8 = analyzer.chain(8)
assert set(cycle_8) == {8, 9}, f"Expected cycle {{8, 9}}, got {cycle_8}"
assert roots[8] is None and roots[9] is None
print("All unit tests passed successfully!")
if __name__ == "__main__":
test_referral_analyzer()
Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Preprocessing | $O(N)$ | $O(N)$ |
chain(u) | $O(L)$ where $L$ is length to root/cycle | $O(L)$ |
compute_all_metrics() | $O(N)$ overall | $O(N)$ overall |
| Top-3 Chains | $O(N \log N)$ sorting leaves | $O(N)$ memory |
- Time Complexity: The 3-state DFS visits every edge and vertex in the functional graph at most twice (once on entry, once when transitioning to
VISITED). Thus, processing all $N$ nodes takes $O(N)$ aggregate time. - Space Complexity: Hash tables (
root_map,depth_map,state) and recursion call stack utilize $O(N)$ space.