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:

  1. read_rows(lines)

    • Parse CSV text lines (starting with header user_id,referred_by) into a list of raw (user_id, referred_by) pairs.
  2. preprocess(rows) -> (parent, report)

    • Clean an iterable of raw (user_id, referred_by) pairs into:
      • parent: a dictionary {user_id: referrer_id} mapping each valid user_id (int) to its inviter (int) or None when the account signed up organically.
      • report: an audit dictionary with keys:
        • "duplicate_rows": count of extra valid rows skipped because that user_id already appeared earlier,
        • "conflicts": sorted list of user_ids where at least one skipped duplicate row disagreed with the earliest kept inviter,
        • "self_referrals": sorted list of user_ids whose kept inviter equals user_id (keep parent[u] = u in parent so cycle checks still see the self-loop),
        • "external_referrers": sorted list of non-None inviter IDs that never appear as keys in parent,
        • "bad_rows": count of skipped rows where user_id is 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" to None.
    • 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_id appears multiple times, retain the earliest valid row encountered.
  3. chain(parent, u)

    • Raise KeyError if u is not a key in parent.
    • Walk upward from u through parent pointers without ever entering an infinite loop:
      • Acyclic path: if the walk terminates at None or at an external inviter (an ID absent from parent), return {"chain": [root, ..., u], "prefix": [], "cycle": []} ordered from earliest ancestor (root) down to u.
      • Cyclic path: if the upward walk revisits a node, return {"chain": None, "prefix": [...], "cycle": [...]} where prefix lists the nodes walked from u before entering the loop (in upward encounter order) and cycle lists the simple loop's nodes starting at the repeated entry node (also in upward encounter order).
  4. roots_and_depths(parent) -> (root, depth)

    • In O(n) total time and O(n) space across all n = 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 every u in parent:
      • root[u]: the earliest ancestor ID (including an external inviter ID when applicable), or None when u's upward walk reaches a cycle.
      • depth[u]: the count of distinct inviters encountered above u along its upward walk (for instance, 0 for an organic root, 1 for a self-loop, 2 for members of a 2-node loop, and 2 for an account whose direct inviter sits on that 2-node loop).
  5. top_chains(parent, k=3)

    • Return up to k longest valid acyclic root -> leaf chains, where a leaf is an acyclic account in parent that nobody in parent lists as their inviter.
    • Order results by decreasing chain length, breaking ties first by smaller root ID and then lexicographically by the full [root, ..., leaf] list.

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^6 and 0 <= len(parent) <= 10^6.
  • Valid account IDs fit in signed 64-bit integers (including values above 2^53).
  • Paths may be up to 10^6 edges deep, so solutions must avoid recursive stack overflow.
  • roots_and_depths(parent) must run in O(n) time and O(n) space for n = len(parent).
  • 1 <= k <= n when n >= 1 (if fewer than k acyclic leaves exist, top_chains returns all of them).

Step-by-step walkthrough

  1. 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 (or None when user signed 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 0 or 1. Walking upward along parent pointers from any account can end in only two ways:

    1. Acyclic tree: the walk reaches a root — either an internal root whose referred_by is None, or an external root (an inviter ID referenced in referred_by that has no row of its own).
    2. Cycle component: the walk eventually revisits a node, tracing a simple loop (a 1-node self-loop like 55 -> 55 or a multi-node ring like 70 <-> 80), optionally with tributary chains feeding into that ring.

    Here is Example 1 (plus external root 500 from Example 2 and deeper tributary node 95 -> 90 to 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 (200 invited by 500, 201 invited by 200), chain(parent, 201) returns [500, 200, 201] and depth[201] = 2. Because 500 has no row of its own, 500 is not a key in parent, root, or depth.
    • 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 above u on its upward walk. When u's path enters a loop, root[u] is None, while depth[u] remains finite (70 <-> 80 has 2 distinct 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].
  2. Clean messy CSV rows first

    Data pipelines break before any graph traversal runs if null strings, spreadsheet-formatted IDs, or duplicate rows slip in. preprocess enforces all four cleaning rules in one linear pass:

    • Null normalization: "", whitespace, "null", "None", "NaN", "NA", "\N", and None all normalize to None.
    • Exact 64-bit integer parsing: nullable integer columns exported from spreadsheets or pandas often carry a trailing ".0" ("200.0"). Stripping ".0" and calling int(text) directly — never int(float(text)) — preserves 64-bit IDs above 2^53 without 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 record user_id in report["conflicts"].
    • Self-invitations and external roots: retain parent[55] = 55 in parent so chain(parent, 55) detects the cycle, while listing 55 in report["self_referrals"] and missing inviter IDs in report["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
    
  3. 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 to walk while recording its list index in a hash map position[node] = index.

    Why maintain both walk and position? Testing next_node in walk on a list scans linearly in O(L) per step (O(L^2) total on deep chains), whereas next_node in position checks a dictionary in O(1) time and immediately gives the slice boundary cycle_start separating 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 order
    

    Notice how parent.get(node) handles external roots automatically: in Example 2 (201 -> 200 -> 500), walk collects [201, 200, 500], parent.get(500) returns None, 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_node
    
  4. Why per-user walks are too slow, and how memoized 3-color walks achieve O(n)

    If 1,000,000 accounts form one long line 1 <- 2 <- ... <- 1,000,000, calling chain(parent, u) independently for every account performs 1 + 2 + ... + n = n(n - 1) / 2 ≈ 5 * 10^11 steps (O(n^2)).

    We reduce total work to O(n) by combining memoization (caching (root[u], depth[u]) the first time u is solved so later walks stop in O(1)) with three-color depth-first search (DFS) — distinguishing unvisited nodes (white), nodes on the active upward stack (gray), and already-solved nodes in root (black). Using an explicit Python list stack instead of recursion avoids Python's ~1,000-frame call-stack limit on 10^6-deep chains.

    Each upward walk from an unsolved account start stops 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 L
    

    Pay 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_cycle handles this cleanly: when popping 90 directly below cycle member 70, base_on_cycle is True, so depth[90] = base_depth without adding 1. Then base_on_cycle resets to False because 90 itself sits outside the cycle ring, so popping 95 below 90 adds + 1 normally!

  5. Implement O(n) roots and depths

    Across the entire outer loop, each account enters stack at most once and leaves stack at most once with O(1) hash-map operations per step, guaranteeing O(n) time and O(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, depth
    
  6. Rank the top-k chains without building all chains upfront

    Maximal acyclic chains end at acyclic leaves — accounts u with root[u] is not None that never appear as another account's inviter. Materializing [root, ..., leaf] for every leaf before sorting could cost O(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 smaller rank[leaf] always corresponds to a lexicographically smaller chain! Then heapq.nsmallest(k, candidates) selects the winning k leaves and calls chain(parent, leaf) at most k times.

    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 result
    
  7. Walk 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 (40 and 25), so top_chains(parent, k=3) returns [[10, 20, 30, 40], [10, 25]].

  8. 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):

  1. Account 10 has no inviter, so root[10] = 10 and depth[10] = 0.
  2. Account 30 pushes [30, 20], sees 20's inviter 10 is already solved, and unwinds: 20 gets (root=10, depth=1), then 30 gets (root=10, depth=2).
  3. Account 70 pushes [70, 80], sees 70 is still on the active stack, and marks {70, 80} as a 2-node loop: root = None, depth = 2.
  4. Account 90 (parent[90] = 70) stops immediately at solved cycle member 70: because 70 is already inside {70, 80}, depth[90] stays 2 (whereas a child 95 -> 90 below 90 gains 90 as a new inviter and gets depth[95] = 3).

Complexity

  • preprocess(rows): O(r + m log m) time and O(n) space, where r is the raw row count, n is the number of distinct valid accounts, and m <= n is the count of flagged IDs. We scan all r rows once using O(1) dictionary lookups, pass over the n kept accounts once, and sort only the flagged audit lists.
  • chain(parent, u): O(L) time and O(L) space, where L is the number of vertices walked from u to its root or around its loop. Every step appends once to walk and checks position in O(1) time.
  • roots_and_depths(parent): O(n) time and O(n) space. Across all n accounts, each account is pushed onto stack at most once (solved accounts are never walked again) and popped once, doing O(1) hash-map work per step.
  • top_chains(parent, k=3): O(n log n) time and O(n) space. Sorting child lists across acyclic tree nodes takes O(n log n) total time, preorder traversal (visiting each parent before its children) takes O(n) time, heapq.nsmallest(k, ...) runs in O(n log k) (O(n) for k = 3), and only the k winning chains are reconstructed.

Edge cases

  • Self-invitation (55 -> 55): chain(parent, 55) spots 55 at index 0 immediately, returning prefix = [], cycle = [55], root[55] = None, and depth[55] = 1.
  • Tributary feeding into a loop (95 -> 90 -> 70 <-> 80): chain(parent, 95) returns prefix = [95, 90] and cycle = [70, 80]; depth[90] = 2 ({70, 80}) and depth[95] = 3 ({90, 70, 80}).
  • External inviter (201 -> 200 -> 500 where 500 has no row): 500 anchors [500, 200, 201], root[201] = 500, depth[201] = 2, and 500 is recorded in report["external_referrers"].
  • Conflicting vs. identical duplicates: ("201", "200.0") followed by ("201", "999") retains 200 and adds 201 to report["conflicts"], whereas identical duplicate rows increment duplicate_rows without adding a conflict.
  • Spreadsheet ".0" suffixes and 64-bit IDs above 2^53: slicing ".0" before int() parses "200.0" and large 64-bit IDs accurately while rejecting lossy "1.2E+15" and booleans.
  • Deep 10^6-node lines or fewer than k leaves: explicit stacks avoid RecursionError, and top_chains cleanly returns fewer than k chains when fewer than k acyclic leaves exist.

Common mistakes

  • Using one global visited set 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 walk on a Python list. Linear scans inside chain(parent, u) degrade a single chain of length L from O(L) to O(L^2).
  • Writing recursive DFS in Python. A valid 10^5- or 10^6-account chain exceeds Python's default call-stack limit (~1,000 frames).
  • Over-counting depth at cycle entry. For 90 -> 70 where 70 <-> 80, inviter 70 is already counted inside depth[70] = 2, so depth[90] is 2, not 3.
  • 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 children adjacency lists first, then run breadth-first search (BFS) — visiting nodes level by level outward from every organic and external root — setting depth[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) inside cycle and 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 guarantees tuple(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 u signs up under an already-processed inviter p, u has out-degree 1 and in-degree 0 (so it cannot close a cycle) and immediately receives root[u] = root[p] and depth[u] = depth[p] (if p sits directly on a cycle ring) or depth[p] + 1 in O(1) time. If retro-edits to an existing account's inviter are allowed, walk upward from the new inviter first to check whether u is reachable (which would form a new loop) and then refresh only u'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 pointer anc[u] with anc[anc[u]] and add their step counts, doubling the hop reach each round (1, 2, 4, 8, ...). Acyclic chains of depth D converge in ceil(log2(D)) rounds (at most 30 joins even for D = 10^9), and any account whose pointer still has a non-null parent after ceil(log2(N)) rounds is guaranteed to sit on or feed into a cycle.

Follow-up questions

Similar questions

More Block (Square) interview questions

All 2 Block (Square) questions →