KatInterview

Analyze Referral Chains and Detect Graph Cycles

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphsdfscycle-detection

Last 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_by may refer to a user_id that 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:

  1. 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.
  2. Single User Path Traversal (chain(u)):

    • Write a function chain(u) that walks upstream from u to 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) where cycle is the list of nodes forming the cycle in encounter order, and prefix is the path of nodes leading into that cycle.
  3. 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 to u (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 = None and chain_depth = None (or mark them as cyclic).
    • Avoid performing full $O(n)$ walks per node; use memoization, graph coloring, or iterative DFS.
  4. Top-3 Longest Acyclic Chains:

    • Extract the top 3 longest maximal acyclic chains (paths from root to a leaf node).
    • Tie-breaking rules:
      1. Primary: Larger path length (number of nodes).
      2. Secondary: Smaller root_ancestor ID.
      3. Tertiary: Lexicographically smaller path array.
  5. 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).

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.