Reconstruct User Referral Graphs and Cycles
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
An invitation ledger records how accounts invited one another into a platform. Each account has at most one inviter, exported as CSV text with header user_id,referred_by where user_id is an integer account ID and referred_by is either an integer account ID or a missing-value marker. Raw exports can contain duplicate user rows, malformed strings, spreadsheet-formatted IDs like "4.0", external inviter IDs absent from the user_id column, self-invitations, and multi-account loops.
Implement five functions to ingest, clean, and analyze this directed invitation graph:
-
read_rows(lines)- Parse CSV text lines (starting with header
user_id,referred_by) into a list of raw(user_id, referred_by)pairs.
- Parse CSV text lines (starting with header
-
preprocess(rows) -> (parent, report)- Clean an iterable of raw
(user_id, referred_by)pairs into:parent: a dictionary{user_id: referrer_id}mapping each validuser_id(int) to its inviter (int) orNonewhen the account signed up organically.report: an audit dictionary with keys:"duplicate_rows": count of extra valid rows skipped because thatuser_idalready appeared earlier,"conflicts": sorted list ofuser_ids where at least one skipped duplicate row disagreed with the earliest kept inviter,"self_referrals": sorted list ofuser_ids whose kept inviter equalsuser_id(keepparent[u] = uinparentso cycle checks still see the self-loop),"external_referrers": sorted list of non-Noneinviter IDs that never appear as keys inparent,"bad_rows": count of skipped rows whereuser_idis missing or either column cannot be parsed as an exact integer.
- Normalize
None, empty/whitespace strings, and case-insensitive markers"null","none","nan","na", and"\N"toNone. - Accept integer strings with a trailing
".0"suffix (such as"200.0"->200) while preserving exact 64-bit integer precision, and reject non-integer decimals ("4.5"), scientific notation ("1.2E+15"), booleans, or non-numeric strings as bad rows. - When a
user_idappears multiple times, retain the earliest valid row encountered.
- Clean an iterable of raw
-
chain(parent, u)- Raise
KeyErrorifuis not a key inparent. - Walk upward from
uthroughparentpointers without ever entering an infinite loop:- Acyclic path: if the walk terminates at
Noneor at an external inviter (an ID absent fromparent), return{"chain": [root, ..., u], "prefix": [], "cycle": []}ordered from earliest ancestor (root) down tou. - Cyclic path: if the upward walk revisits a node, return
{"chain": None, "prefix": [...], "cycle": [...]}whereprefixlists the nodes walked fromubefore entering the loop (in upward encounter order) andcyclelists the simple loop's nodes starting at the repeated entry node (also in upward encounter order).
- Acyclic path: if the walk terminates at
- Raise
-
roots_and_depths(parent) -> (root, depth)- In
O(n)total time andO(n)space across alln = len(parent)accounts (reusing work across overlapping paths rather than re-walking from scratch per user, and without hitting Python's recursion limit on deep paths), compute two dictionaries keyed by everyuinparent:root[u]: the earliest ancestor ID (including an external inviter ID when applicable), orNonewhenu's upward walk reaches a cycle.depth[u]: the count of distinct inviters encountered aboveualong its upward walk (for instance,0for an organic root,1for a self-loop,2for members of a 2-node loop, and2for an account whose direct inviter sits on that 2-node loop).
- In
-
top_chains(parent, k=3)- Return up to
klongest valid acyclicroot -> leafchains, where a leaf is an acyclic account inparentthat nobody inparentlists as their inviter. - Order results by decreasing chain length, breaking ties first by smaller
rootID and then lexicographically by the full[root, ..., leaf]list.
- Return up to
Examples
Example 1
Input CSV (lines):
user_id,referred_by
10,
20,10
25,10
30,20
40,30
55,55
70,80
80,70
90,70
Outputs:
- preprocess(read_rows(lines)) returns:
- parent = {10: None, 20: 10, 25: 10, 30: 20, 40: 30, 55: 55, 70: 80, 80: 70, 90: 70}
- report = {"duplicate_rows": 0, "conflicts": [], "self_referrals": [55], "external_referrers": [], "bad_rows": 0}
- chain(parent, 40) -> {"chain": [10, 20, 30, 40], "prefix": [], "cycle": []}
- chain(parent, 55) -> {"chain": None, "prefix": [], "cycle": [55]}
- chain(parent, 70) -> {"chain": None, "prefix": [], "cycle": [70, 80]}
- chain(parent, 90) -> {"chain": None, "prefix": [90], "cycle": [70, 80]}
- roots_and_depths(parent) returns:
- root = {10: 10, 20: 10, 25: 10, 30: 10, 40: 10, 55: None, 70: None, 80: None, 90: None}
- depth = {10: 0, 20: 1, 25: 1, 30: 2, 40: 3, 55: 1, 70: 2, 80: 2, 90: 2}
- top_chains(parent, k=3) -> [[10, 20, 30, 40], [10, 25]]
Walk-through: Account 10 is an organic root (depth = 0) with two leaf descendants: 40 along 10 -> 20 -> 30 -> 40 (depth = 3) and 25 along 10 -> 25 (depth = 1). Account 55 invited itself (cycle = [55]), while 70 and 80 form a 2-node loop (70 <-> 80). Account 90 was invited by 70, so walking upward from 90 visits 90 before entering 70 -> 80, giving prefix = [90], cycle = [70, 80], and 2 distinct inviters ({70, 80}).
Example 2
Input (rows):
rows = [
("200", "500"),
("201", "200.0"),
("201", "999"),
("100", "null"),
("102", "100"),
("101", "100"),
("103", "102"),
("104", "101"),
("bad", "100"),
]
Outputs:
- preprocess(rows) returns:
- parent = {200: 500, 201: 200, 100: None, 102: 100, 101: 100, 103: 102, 104: 101}
- report = {"duplicate_rows": 1, "conflicts": [201], "self_referrals": [], "external_referrers": [500], "bad_rows": 1}
- chain(parent, 201) -> {"chain": [500, 200, 201], "prefix": [], "cycle": []}
- top_chains(parent, k=2) -> [[100, 101, 104], [100, 102, 103]]
Walk-through: "200.0" parses cleanly to 200, the conflicting duplicate ("201", "999") is ignored while flagging 201 in conflicts, "bad" increments bad_rows, and 500 has no row of its own so it becomes an external root ([500, 200, 201]). All three maximal acyclic chains ([100, 101, 104], [100, 102, 103], and [500, 200, 201]) have length 3; root 100 < 500 wins the first tie-breaker, and [100, 101, 104] precedes [100, 102, 103] lexicographically even though leaf ID 103 < 104.
Constraints
0 <= len(rows) <= 10^6and0 <= len(parent) <= 10^6.- Valid account IDs fit in signed 64-bit integers (including values above
2^53). - Paths may be up to
10^6edges deep, so solutions must avoid recursive stack overflow. roots_and_depths(parent)must run inO(n)time andO(n)space forn = len(parent).1 <= k <= nwhenn >= 1(if fewer thankacyclic leaves exist,top_chainsreturns all of them).
Step-by-step walkthrough
Understand the invitation graph and its shapes
Each account has at most one inviter, so once the CSV is cleaned we can represent the entire ledger in a single dictionary
parent[user] = referrer(orNonewhenusersigned up organically).Because every vertex has at most one outgoing edge pointing upward to its inviter, this structure is a partial functional graph — a directed graph where every node has out-degree
0or1. Walking upward alongparentpointers from any account can end in only two ways:- Acyclic tree: the walk reaches a root — either an internal root whose
referred_byisNone, or an external root (an inviter ID referenced inreferred_bythat has no row of its own). - Cycle component: the walk eventually revisits a node, tracing a simple loop (a 1-node self-loop like
55 -> 55or a multi-node ring like70 <-> 80), optionally with tributary chains feeding into that ring.
Here is Example 1 (plus external root
500from Example 2 and deeper tributary node95 -> 90to show every shape):Acyclic tree (root 10) External root Self-loop 2-node loop + tributary 10 500 +-+ 70 <---> 80 / \ ^ v | ^ 20 25 | 55 | | 200 90 30 ^ ^ | | | 40 201 95 ([10, 20, 30, 40], depth=3)Verify the exact contracts required by
starter.py:- External inviters stand at the front of chains: in Example 2 (
200invited by500,201invited by200),chain(parent, 201)returns[500, 200, 201]anddepth[201] = 2. Because500has no row of its own,500is not a key inparent,root, ordepth. chain(parent, u)returns{"chain": [root, ..., u], "prefix": [], "cycle": []}when acyclic, or{"chain": None, "prefix": [...], "cycle": [...]}in upward encounter order when cyclic.depth[u]counts distinct inviters aboveuon its upward walk. Whenu's path enters a loop,root[u]isNone, whiledepth[u]remains finite (70 <-> 80has2distinct inviters{70, 80}).top_chains(parent, k=3)considers only maximal acyclic chains ending at a leaf (an account nobody else lists as their inviter), preventing[10, 20, 30, 40]from competing against its own prefixes[10, 20, 30]and[10, 20].
- Acyclic tree: the walk reaches a root — either an internal root whose
Clean messy CSV rows first
Data pipelines break before any graph traversal runs if null strings, spreadsheet-formatted IDs, or duplicate rows slip in.
preprocessenforces all four cleaning rules in one linear pass:- Null normalization:
"", whitespace,"null","None","NaN","NA","\N", andNoneall normalize toNone. - Exact 64-bit integer parsing: nullable integer columns exported from spreadsheets or pandas often carry a trailing
".0"("200.0"). Stripping".0"and callingint(text)directly — neverint(float(text))— preserves 64-bit IDs above2^53without rounding and rejects lossy strings like"1.2E+15"as bad rows. - Earliest-row deduplication: keep the first valid row seen for each
user_id. If a subsequent duplicate row specifies a different inviter, keep the original inviter and recorduser_idinreport["conflicts"]. - Self-invitations and external roots: retain
parent[55] = 55inparentsochain(parent, 55)detects the cycle, while listing55inreport["self_referrals"]and missing inviter IDs inreport["external_referrers"].
from typing import Dict, Iterable, List, Optional, Set, Tuple import csv # Lowercased strings that represent a missing referrer in messy CSV exports. NULL_STRINGS = {"", "null", "none", "nan", "na", "\\n"} def read_rows(lines: Iterable[str]) -> List[Tuple[Optional[str], Optional[str]]]: """Parse referrals.csv lines (header: user_id,referred_by) into raw (user_id, referred_by) pairs.""" rows: List[Tuple[Optional[str], Optional[str]]] = [] for record in csv.DictReader(lines): rows.append((record["user_id"], record["referred_by"])) return rows def to_int(value) -> Optional[int]: """Parse a raw ID into an int, or None for null-like markers. Accepts integer strings ("4") and pandas float-formatted integers ("4.0"). Raises ValueError on malformed values ("abc", "4.5", "1.2E+15", booleans). """ if value is None: return None # Reject booleans explicitly because bool is a subclass of int in Python. if isinstance(value, bool): raise ValueError("boolean is not a valid user id") if isinstance(value, int): return value text = str(value).strip() if text.lower() in NULL_STRINGS: return None # Nullable integer columns exported by pandas appear with a trailing ".0". if text.endswith(".0"): text = text[:-2] # Convert directly with int() (never float()) so 64-bit IDs above 2^53 stay exact. return int(text) def preprocess(rows) -> Tuple[Dict[int, Optional[int]], Dict[str, object]]: """Clean raw (user_id, referred_by) pairs into a parent map and an audit report.""" # parent: {user_id: referrer_id or None}, e.g. {10: None, 20: 10, 55: 55} parent: Dict[int, Optional[int]] = {} duplicate_rows = 0 bad_rows = 0 conflicts: Set[int] = set() # Phase 1: parse IDs, skip malformed rows, and deduplicate keeping earliest parent. for raw_user, raw_referrer in rows: try: user = to_int(raw_user) referrer = to_int(raw_referrer) except ValueError: bad_rows += 1 continue if user is None: bad_rows += 1 continue if user in parent: duplicate_rows += 1 # Flag a conflict only when a duplicate row disagrees with the kept referrer. if parent[user] != referrer: conflicts.add(user) continue parent[user] = referrer # Phase 2: keep self-referrals in parent (so cycle detection sees them), and record # external referrers (IDs referenced in referred_by that have no row of their own). self_referrals: List[int] = [] external_referrers: Set[int] = set() for user, referrer in parent.items(): if referrer == user: self_referrals.append(user) if referrer is not None and referrer not in parent: external_referrers.add(referrer) report: Dict[str, object] = { "duplicate_rows": duplicate_rows, "conflicts": sorted(conflicts), "self_referrals": sorted(self_referrals), "external_referrers": sorted(external_referrers), "bad_rows": bad_rows, } return parent, report- Null normalization:
Walk upward from one account to extract a chain or cycle
To implement
chain(parent, u), step upward (u -> parent[u] -> ...), appending each visited node towalkwhile recording its list index in a hash mapposition[node] = index.Why maintain both
walkandposition? Testingnext_node in walkon a list scans linearly inO(L)per step (O(L^2)total on deep chains), whereasnext_node in positionchecks a dictionary inO(1)time and immediately gives the slice boundarycycle_startseparating the tributary prefix from the simple cycle!Case A — Acyclic walk chain(parent, 40): walk = [40, 30, 20, 10] next_node = parent.get(10) -> None (reached root!) reverse walk -> [10, 20, 30, 40] Case B — Tributary into a cycle (95 -> 90 -> 70 <-> 80): index: 0 1 2 3 walk = [95, 90, 70, 80] next_node = parent.get(80) -> 70, already in position at cycle_start = 2! walk[:2] = [95, 90] <- acyclic prefix in upward encounter order walk[2:] = [70, 80] <- simple cycle in upward encounter orderNotice how
parent.get(node)handles external roots automatically: in Example 2 (201 -> 200 -> 500),walkcollects[201, 200, 500],parent.get(500)returnsNone, and reversing yields[500, 200, 201].from typing import Dict, List, Optional def chain(parent: Dict[int, Optional[int]], u: int) -> Dict[str, Optional[List[int]]]: """Return u's root-to-u referral chain, or the prefix and simple cycle if cyclic.""" if u not in parent: raise KeyError(u) # walk: upward path [u, referrer_of_u, ...] in encounter order. walk: List[int] = [] # position: {node_id: index_in_walk} so repeating a node is detected in O(1) time. position: Dict[int, int] = {} node = u while True: position[node] = len(walk) walk.append(node) # parent.get(node) is None both for an internal root and for an external referrer. next_node = parent.get(node) if next_node is None: walk.reverse() return {"chain": walk, "prefix": [], "cycle": []} if next_node in position: cycle_start = position[next_node] prefix_nodes = walk[:cycle_start] cycle_nodes = walk[cycle_start:] return {"chain": None, "prefix": prefix_nodes, "cycle": cycle_nodes} node = next_nodeWhy per-user walks are too slow, and how memoized 3-color walks achieve O(n)
If
1,000,000accounts form one long line1 <- 2 <- ... <- 1,000,000, callingchain(parent, u)independently for every account performs1 + 2 + ... + n = n(n - 1) / 2 ≈ 5 * 10^11steps (O(n^2)).We reduce total work to
O(n)by combining memoization (caching(root[u], depth[u])the first timeuis solved so later walks stop inO(1)) with three-color depth-first search (DFS) — distinguishing unvisited nodes (white), nodes on the active upwardstack(gray), and already-solved nodes inroot(black). Using an explicit Python liststackinstead of recursion avoids Python's ~1,000-frame call-stack limit on10^6-deep chains.Each upward walk from an unsolved account
startstops at one of four base cases:Base Case 1: node is None -> top of stack is an organic root (root=top, depth=0) Base Case 2: node not in parent -> node is an external root (base_root=node, base_depth=0) Base Case 3: node in root (black) -> reuse cached (root[node], depth[node]) in O(1) Base Case 4: node in stack_index (gray) -> stack[pos:] is a newly discovered cycle of length LPay close attention when unwinding a tributary path feeding into a cycle (
95 -> 90 -> 70 <-> 80):Node | Distinct inviters above node | depth | Reason -----+------------------------------+-------+------------------------------------------------- 70 | {80, 70} | 2 | Cycle of length L = 2 80 | {70, 80} | 2 | Cycle of length L = 2 90 | {70, 80} | 2 | 90's inviter is 70, ALREADY counted in {70, 80}! 95 | {90, 70, 80} | 3 | 95's inviter is 90, outside the ring (+1)Tracking a boolean
base_on_cyclehandles this cleanly: when popping90directly below cycle member70,base_on_cycleisTrue, sodepth[90] = base_depthwithout adding1. Thenbase_on_cycleresets toFalsebecause90itself sits outside the cycle ring, so popping95below90adds+ 1normally!Implement O(n) roots and depths
Across the entire outer loop, each account enters
stackat most once and leavesstackat most once withO(1)hash-map operations per step, guaranteeingO(n)time andO(n)memory.from typing import Dict, List, Optional, Set, Tuple def roots_and_depths(parent: Dict[int, Optional[int]]) -> Tuple[Dict[int, Optional[int]], Dict[int, int]]: """Compute (root[u], depth[u]) for all users in O(n) total time and O(n) memory.""" # root: {user_id: earliest_ancestor_id or None}; None when u's path reaches a cycle. root: Dict[int, Optional[int]] = {} # depth: {user_id: count_of_distinct_referrers_above_user}. depth: Dict[int, int] = {} # on_cycle: users sitting directly on a cycle ring (e.g. {55, 70, 80}). on_cycle: Set[int] = set() for start in parent: if start in root: continue # Phase 1: walk upward from start using an explicit stack (avoiding Python's # recursion limit) until we hit a root, external root, solved user, or cycle. stack: List[int] = [] stack_index: Dict[int, int] = {} node = start while True: stack_index[node] = len(stack) stack.append(node) node = parent[node] if node is None or node not in parent or node in root or node in stack_index: break # Phase 2: solve the stopping point so we know (base_root, base_depth, base_on_cycle). if node is None: # The last user pushed has no referrer, so it is its own root with depth 0. top_user = stack.pop() root[top_user] = top_user depth[top_user] = 0 base_root, base_depth, base_on_cycle = top_user, 0, False elif node not in parent: # External referrer: acts as a root at depth 0 for the user just below it. base_root, base_depth, base_on_cycle = node, 0, False elif node in root: # Already solved in an earlier walk: reuse its memoized answer in O(1). base_root = root[node] base_depth = depth[node] base_on_cycle = node in on_cycle else: # node is in stack_index: stack[cycle_pos:] forms a newly discovered cycle. cycle_pos = stack_index[node] cycle_members = stack[cycle_pos:] del stack[cycle_pos:] cycle_len = len(cycle_members) for member in cycle_members: root[member] = None depth[member] = cycle_len on_cycle.add(member) base_root, base_depth, base_on_cycle = None, cycle_len, True # Phase 3: unwind remaining tributary users from highest ancestor down to start. while stack: user = stack.pop() root[user] = base_root if base_on_cycle: # user's referrer sits directly on the cycle, so that referrer is ALREADY # counted inside base_depth (e.g. 90 -> 70 <-> 80 has ancestors {70, 80}, count 2). depth[user] = base_depth else: depth[user] = base_depth + 1 base_depth = depth[user] # Once we step onto user, user itself is outside the cycle ring, so the next # child below user WILL gain user as 1 brand-new distinct referrer. base_on_cycle = False return root, depthRank the top-k chains without building all chains upfront
Maximal acyclic chains end at acyclic leaves — accounts
uwithroot[u] is not Nonethat never appear as another account's inviter. Materializing[root, ..., leaf]for every leaf before sorting could costO(n^2)time and memory when a long shared trunk branches into hundreds of thousands of leaves.How do we break lexicographic ties between two equal-length chains under the same root in
O(1)? Assign preorder traversal visit numbers — visiting each parent before its children, and visiting smaller child IDs first:Example 2 subtree under root 100: Preorder visit order (smallest child first): 100 100 (rank 0) -> 101 (rank 1) -> 104 (rank 2) / \ -> 102 (rank 3) -> 103 (rank 4) 101 102 | | Compare [100, 101, 104] vs. [100, 102, 103]: 104 103 - Leaf ID comparison (103 < 104) picks [100, 102, 103] (WRONG!) - Preorder rank (rank[104]=2 < rank[103]=4) picks [100, 101, 104] (RIGHT!)Wherever two root-to-leaf paths first diverge, preorder finishes the entire subtree of the smaller child ID (
101) before visiting the larger child ID (102), so smallerrank[leaf]always corresponds to a lexicographically smaller chain! Thenheapq.nsmallest(k, candidates)selects the winningkleaves and callschain(parent, leaf)at mostktimes.from typing import Dict, Iterable, List, Optional, Set, Tuple import heapq def preorder_ranks(children: Dict[int, List[int]], roots: Iterable[int]) -> Dict[int, int]: """Assign preorder visit numbers across acyclic trees, visiting smaller child IDs first.""" # rank: {node_id: preorder_visit_number}, used to break lexicographic chain ties in O(1). rank: Dict[int, int] = {} for tree_root in sorted(roots): stack = [tree_root] while stack: node = stack.pop() rank[node] = len(rank) # Push children in descending order so the smallest ID is popped next (LIFO). ordered_children = sorted(children.get(node, []), reverse=True) stack.extend(ordered_children) return rank def top_chains(parent: Dict[int, Optional[int]], k: int = 3) -> List[List[int]]: """Return the k longest acyclic root-to-leaf chains with root and lexicographic tie-breaks.""" root, depth = roots_and_depths(parent) # children: {referrer_id: [referred_user_ids]} for acyclic components only. children: Dict[int, List[int]] = {} referrers: Set[int] = set() acyclic_roots: Set[int] = set() for user, referrer in parent.items(): if referrer is not None: referrers.add(referrer) if root[user] is None: continue acyclic_roots.add(root[user]) if referrer is not None: children.setdefault(referrer, []).append(user) rank = preorder_ranks(children, acyclic_roots) # Only acyclic leaves (users nobody else refers) represent maximal chains. # Tuple (-depth, root_id, preorder_rank, leaf_id) sorts longest first, then smallest root, # then lexicographically smallest root-to-leaf list without building every chain upfront. candidates: List[Tuple[int, int, int, int]] = [] for user in parent: if root[user] is not None and user not in referrers: candidates.append((-depth[user], root[user], rank[user], user)) best_leaves = heapq.nsmallest(k, candidates) result: List[List[int]] = [] for _, _, _, leaf in best_leaves: leaf_chain = chain(parent, leaf)["chain"] if leaf_chain is not None: result.append(leaf_chain) return resultWalk through Example 1 end to end
Tracing all nine accounts from Example 1 shows every case working together:
user | referred_by | root[user] | depth[user] | chain(parent, user) -----+-------------+------------+-------------+---------------------------------------------- 10 | None | 10 | 0 | chain=[10] 20 | 10 | 10 | 1 | chain=[10, 20] 25 | 10 | 10 | 1 | chain=[10, 25] <- acyclic leaf #2 30 | 20 | 10 | 2 | chain=[10, 20, 30] 40 | 30 | 10 | 3 | chain=[10, 20, 30, 40] <- acyclic leaf #1 55 | 55 | None | 1 | prefix=[], cycle=[55] (self-loop) 70 | 80 | None | 2 | prefix=[], cycle=[70, 80] (2-node loop) 80 | 70 | None | 2 | prefix=[], cycle=[80, 70] (2-node loop) 90 | 70 | None | 2 | prefix=[90], cycle=[70, 80] (tributary)Only two acyclic leaves exist (
40and25), sotop_chains(parent, k=3)returns[[10, 20, 30, 40], [10, 25]].Complete solution
from typing import Dict, Iterable, List, Optional, Set, Tuple import csv import heapq # Lowercased strings that represent a missing referrer in messy CSV exports. NULL_STRINGS = {"", "null", "none", "nan", "na", "\\n"} def read_rows(lines: Iterable[str]) -> List[Tuple[Optional[str], Optional[str]]]: """Parse referrals.csv lines (header: user_id,referred_by) into raw (user_id, referred_by) pairs.""" rows: List[Tuple[Optional[str], Optional[str]]] = [] for record in csv.DictReader(lines): rows.append((record["user_id"], record["referred_by"])) return rows def to_int(value) -> Optional[int]: """Parse a raw ID into an int, or None for null-like markers. Accepts integer strings ("4") and pandas float-formatted integers ("4.0"). Raises ValueError on malformed values ("abc", "4.5", "1.2E+15", booleans). """ if value is None: return None # Reject booleans explicitly because bool is a subclass of int in Python. if isinstance(value, bool): raise ValueError("boolean is not a valid user id") if isinstance(value, int): return value text = str(value).strip() if text.lower() in NULL_STRINGS: return None # Nullable integer columns exported by pandas appear with a trailing ".0". if text.endswith(".0"): text = text[:-2] # Convert directly with int() (never float()) so 64-bit IDs above 2^53 stay exact. return int(text) def preprocess(rows) -> Tuple[Dict[int, Optional[int]], Dict[str, object]]: """Clean raw (user_id, referred_by) pairs into a parent map and an audit report.""" # parent: {user_id: referrer_id or None}, e.g. {10: None, 20: 10, 55: 55} parent: Dict[int, Optional[int]] = {} duplicate_rows = 0 bad_rows = 0 conflicts: Set[int] = set() # Phase 1: parse IDs, skip malformed rows, and deduplicate keeping earliest parent. for raw_user, raw_referrer in rows: try: user = to_int(raw_user) referrer = to_int(raw_referrer) except ValueError: bad_rows += 1 continue if user is None: bad_rows += 1 continue if user in parent: duplicate_rows += 1 # Flag a conflict only when a duplicate row disagrees with the kept referrer. if parent[user] != referrer: conflicts.add(user) continue parent[user] = referrer # Phase 2: keep self-referrals in parent (so cycle detection sees them), and record # external referrers (IDs referenced in referred_by that have no row of their own). self_referrals: List[int] = [] external_referrers: Set[int] = set() for user, referrer in parent.items(): if referrer == user: self_referrals.append(user) if referrer is not None and referrer not in parent: external_referrers.add(referrer) report: Dict[str, object] = { "duplicate_rows": duplicate_rows, "conflicts": sorted(conflicts), "self_referrals": sorted(self_referrals), "external_referrers": sorted(external_referrers), "bad_rows": bad_rows, } return parent, report def chain(parent: Dict[int, Optional[int]], u: int) -> Dict[str, Optional[List[int]]]: """Return u's root-to-u referral chain, or the prefix and simple cycle if cyclic.""" if u not in parent: raise KeyError(u) # walk: upward path [u, referrer_of_u, ...] in encounter order. walk: List[int] = [] # position: {node_id: index_in_walk} so repeating a node is detected in O(1) time. position: Dict[int, int] = {} node = u while True: position[node] = len(walk) walk.append(node) # parent.get(node) is None both for an internal root and for an external referrer. next_node = parent.get(node) if next_node is None: walk.reverse() return {"chain": walk, "prefix": [], "cycle": []} if next_node in position: cycle_start = position[next_node] prefix_nodes = walk[:cycle_start] cycle_nodes = walk[cycle_start:] return {"chain": None, "prefix": prefix_nodes, "cycle": cycle_nodes} node = next_node def roots_and_depths(parent: Dict[int, Optional[int]]) -> Tuple[Dict[int, Optional[int]], Dict[int, int]]: """Compute (root[u], depth[u]) for all users in O(n) total time and O(n) memory.""" # root: {user_id: earliest_ancestor_id or None}; None when u's path reaches a cycle. root: Dict[int, Optional[int]] = {} # depth: {user_id: count_of_distinct_referrers_above_user}. depth: Dict[int, int] = {} # on_cycle: users sitting directly on a cycle ring (e.g. {55, 70, 80}). on_cycle: Set[int] = set() for start in parent: if start in root: continue # Phase 1: walk upward from start using an explicit stack (avoiding Python's # recursion limit) until we hit a root, external root, solved user, or cycle. stack: List[int] = [] stack_index: Dict[int, int] = {} node = start while True: stack_index[node] = len(stack) stack.append(node) node = parent[node] if node is None or node not in parent or node in root or node in stack_index: break # Phase 2: solve the stopping point so we know (base_root, base_depth, base_on_cycle). if node is None: # The last user pushed has no referrer, so it is its own root with depth 0. top_user = stack.pop() root[top_user] = top_user depth[top_user] = 0 base_root, base_depth, base_on_cycle = top_user, 0, False elif node not in parent: # External referrer: acts as a root at depth 0 for the user just below it. base_root, base_depth, base_on_cycle = node, 0, False elif node in root: # Already solved in an earlier walk: reuse its memoized answer in O(1). base_root = root[node] base_depth = depth[node] base_on_cycle = node in on_cycle else: # node is in stack_index: stack[cycle_pos:] forms a newly discovered cycle. cycle_pos = stack_index[node] cycle_members = stack[cycle_pos:] del stack[cycle_pos:] cycle_len = len(cycle_members) for member in cycle_members: root[member] = None depth[member] = cycle_len on_cycle.add(member) base_root, base_depth, base_on_cycle = None, cycle_len, True # Phase 3: unwind remaining tributary users from highest ancestor down to start. while stack: user = stack.pop() root[user] = base_root if base_on_cycle: # user's referrer sits directly on the cycle, so that referrer is ALREADY # counted inside base_depth (e.g. 90 -> 70 <-> 80 has ancestors {70, 80}, count 2). depth[user] = base_depth else: depth[user] = base_depth + 1 base_depth = depth[user] # Once we step onto user, user itself is outside the cycle ring, so the next # child below user WILL gain user as 1 brand-new distinct referrer. base_on_cycle = False return root, depth def preorder_ranks(children: Dict[int, List[int]], roots: Iterable[int]) -> Dict[int, int]: """Assign preorder visit numbers across acyclic trees, visiting smaller child IDs first.""" # rank: {node_id: preorder_visit_number}, used to break lexicographic chain ties in O(1). rank: Dict[int, int] = {} for tree_root in sorted(roots): stack = [tree_root] while stack: node = stack.pop() rank[node] = len(rank) # Push children in descending order so the smallest ID is popped next (LIFO). ordered_children = sorted(children.get(node, []), reverse=True) stack.extend(ordered_children) return rank def top_chains(parent: Dict[int, Optional[int]], k: int = 3) -> List[List[int]]: """Return the k longest acyclic root-to-leaf chains with root and lexicographic tie-breaks.""" root, depth = roots_and_depths(parent) # children: {referrer_id: [referred_user_ids]} for acyclic components only. children: Dict[int, List[int]] = {} referrers: Set[int] = set() acyclic_roots: Set[int] = set() for user, referrer in parent.items(): if referrer is not None: referrers.add(referrer) if root[user] is None: continue acyclic_roots.add(root[user]) if referrer is not None: children.setdefault(referrer, []).append(user) rank = preorder_ranks(children, acyclic_roots) # Only acyclic leaves (users nobody else refers) represent maximal chains. # Tuple (-depth, root_id, preorder_rank, leaf_id) sorts longest first, then smallest root, # then lexicographically smallest root-to-leaf list without building every chain upfront. candidates: List[Tuple[int, int, int, int]] = [] for user in parent: if root[user] is not None and user not in referrers: candidates.append((-depth[user], root[user], rank[user], user)) best_leaves = heapq.nsmallest(k, candidates) result: List[List[int]] = [] for _, _, _, leaf in best_leaves: leaf_chain = chain(parent, leaf)["chain"] if leaf_chain is not None: result.append(leaf_chain) return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture every new member writing down the single friend who invited them on a badge. Tracing someone's invitation chain just means following badges upward — "30 was invited by 20, 20 was invited by 10" — until you either reach an organic founder whose badge is blank or loop around a closed ring of accounts that somehow invited one another. Once you stamp each person's founder and distance directly onto their badge (memoization — caching already-computed results so they are never recomputed), anyone else whose chain merges into 20 gets their answer in a single lookup!
Re-walking from scratch for every account breaks down at scale: on a single 1,000,000-account chain, repeating every prefix takes roughly 5 * 10^11 steps (O(n^2)). Plain recursion also crashes Python because deep chains blow past Python's ~1,000-frame call-stack limit, and a single global visited set mistakes "I merged into a harmless account solved on an earlier walk" for "I looped back onto my current active walk."
Watch how an explicit walk stack solves Example 1's components (10 <- 20 <- 30, plus loop 70 <-> 80 with tributary 90 -> 70):
- Account
10has no inviter, soroot[10] = 10anddepth[10] = 0. - Account
30pushes[30, 20], sees20's inviter10is already solved, and unwinds:20gets(root=10, depth=1), then30gets(root=10, depth=2). - Account
70pushes[70, 80], sees70is still on the active stack, and marks{70, 80}as a 2-node loop:root = None,depth = 2. - Account
90(parent[90] = 70) stops immediately at solved cycle member70: because70is already inside{70, 80},depth[90]stays2(whereas a child95 -> 90below90gains90as a new inviter and getsdepth[95] = 3).
Complexity
preprocess(rows):O(r + m log m)time andO(n)space, whereris the raw row count,nis the number of distinct valid accounts, andm <= nis the count of flagged IDs. We scan allrrows once usingO(1)dictionary lookups, pass over thenkept accounts once, and sort only the flagged audit lists.chain(parent, u):O(L)time andO(L)space, whereLis the number of vertices walked fromuto its root or around its loop. Every step appends once towalkand checkspositioninO(1)time.roots_and_depths(parent):O(n)time andO(n)space. Across allnaccounts, each account is pushed ontostackat most once (solved accounts are never walked again) and popped once, doingO(1)hash-map work per step.top_chains(parent, k=3):O(n log n)time andO(n)space. Sorting child lists across acyclic tree nodes takesO(n log n)total time, preorder traversal (visiting each parent before its children) takesO(n)time,heapq.nsmallest(k, ...)runs inO(n log k)(O(n)fork = 3), and only thekwinning chains are reconstructed.
Edge cases
- Self-invitation (
55 -> 55):chain(parent, 55)spots55at index0immediately, returningprefix = [],cycle = [55],root[55] = None, anddepth[55] = 1. - Tributary feeding into a loop (
95 -> 90 -> 70 <-> 80):chain(parent, 95)returnsprefix = [95, 90]andcycle = [70, 80];depth[90] = 2({70, 80}) anddepth[95] = 3({90, 70, 80}). - External inviter (
201 -> 200 -> 500where500has no row):500anchors[500, 200, 201],root[201] = 500,depth[201] = 2, and500is recorded inreport["external_referrers"]. - Conflicting vs. identical duplicates:
("201", "200.0")followed by("201", "999")retains200and adds201toreport["conflicts"], whereas identical duplicate rows incrementduplicate_rowswithout adding a conflict. - Spreadsheet
".0"suffixes and 64-bit IDs above2^53: slicing".0"beforeint()parses"200.0"and large 64-bit IDs accurately while rejecting lossy"1.2E+15"and booleans. - Deep
10^6-node lines or fewer thankleaves: explicit stacks avoidRecursionError, andtop_chainscleanly returns fewer thankchains when fewer thankacyclic leaves exist.
Common mistakes
- Using one global
visitedset for cycle detection. Hitting an account finished during an earlier walk is a DAG/tree merge, not a cycle; only repeating an account on the current walk stack (stack_index) closes a cycle. - Testing
next_node in walkon a Python list. Linear scans insidechain(parent, u)degrade a single chain of lengthLfromO(L)toO(L^2). - Writing recursive DFS in Python. A valid
10^5- or10^6-account chain exceeds Python's default call-stack limit (~1,000frames). - Over-counting
depthat cycle entry. For90 -> 70where70 <-> 80, inviter70is already counted insidedepth[70] = 2, sodepth[90]is2, not3. - Breaking equal-length ties by leaf ID instead of preorder rank. Comparing leaf IDs (
103 < 104) wrongly puts[100, 102, 103]ahead of[100, 101, 104].
Alternative approaches
- Weighted Union-Find (disjoint-set union): Union-Find maintains connected components and a representative root per set. Augmenting parent pointers with path-length weights supports near-linear root and depth queries, though closing an edge within an already-connected component still requires explicit cycle-length handling.
- Top-down BFS from roots: Build
childrenadjacency lists first, then run breadth-first search (BFS) — visiting nodes level by level outward from every organic and external root — settingdepth[child] = depth[parent] + 1. Accounts unreached by BFS belong to cycle components and are resolved in a second pass. - Warehouse Recursive CTE: A recursive common table expression (CTE) repeatedly self-joins a SQL table to walk parent links level by level, which works cleanly for shallow hierarchies when guarded by a visited-ID array or hop cap.
Follow-up questions
- How can you canonicalize detected cycles so every member of the same loop produces the exact same cycle key? Locate the index of
min(cycle)insidecycleand rotate the list so that smallest account ID appears first (for instance,[80, 70]rotates to[70, 80]). Because every vertex on a simple directed loop traverses the exact same ring of accounts in the same cyclic order, rotating to the minimum ID guaranteestuple(canonical_cycle)is identical regardless of where the upward walk entered the loop. - How would you update roots and depths incrementally as live signup events arrive? When a brand-new account
usigns up under an already-processed inviterp,uhas out-degree1and in-degree0(so it cannot close a cycle) and immediately receivesroot[u] = root[p]anddepth[u] = depth[p](ifpsits directly on a cycle ring) ordepth[p] + 1inO(1)time. If retro-edits to an existing account's inviter are allowed, walk upward from the new inviter first to check whetheruis reachable (which would form a new loop) and then refresh onlyu's downstream subtree. - What algorithm computes referral roots and depths when billions of user edges live in a distributed warehouse? Run pointer jumping (path doubling) across distributed Spark or SQL joins: in round
t, join each account's current ancestor pointeranc[u]withanc[anc[u]]and add their step counts, doubling the hop reach each round (1, 2, 4, 8, ...). Acyclic chains of depthDconverge inceil(log2(D))rounds (at most30joins even forD = 10^9), and any account whose pointer still has a non-null parent afterceil(log2(N))rounds is guaranteed to sit on or feed into a cycle.
Follow-up questions
- How can you canonicalize detected cycles so every member of the same loop produces the exact same cycle key?
- How would you update roots and depths incrementally as live signup events arrive?
- What algorithm computes referral roots and depths when billions of user edges live in a distributed warehouse?
Similar questions
- Referral Attribution Metrics Using Left Joins
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One