User Action Sequence Prefix Tree

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Write a function build_summary(logs: List[Tuple[int, int, str]]) -> str that turns raw event records into a hierarchical text summary of user action funnels.

Every record in logs is a 3-tuple (user_id, time, action) describing an action string triggered by user_id at integer timestamp time. Records from different users are interleaved and may appear out of chronological order.

Construct and render the summary according to the following rules:

  1. Chronological per-user timelines: Separate events by user_id and order each user's events by ascending time. Whenever two events belonging to the same user have identical time values, keep them in the relative order in which they appeared in logs.
  2. Prefix tree construction: Insert user timelines into a prefix tree one user at a time in strictly ascending user_id order. Every path from the virtual root down to a tree node represents a contiguous starting prefix of actions, and each node records how many distinct users reached that exact prefix.
  3. Consecutive or repeated actions: Each event in a user's timeline advances one level deeper in the tree, even if the same action label repeats. For instance, "home" -> "search" -> "search" visits "home" at depth 0, "search" at depth 1, and a separate child "search" beneath it at depth 2. A single user adds 1 to each visited node's user count.
  4. Sibling ordering: Under the root and under every internal node, child branches retain the exact order in which they were first created during the ascending-user_id insertion pass.
  5. Text rendering: Output one line per tree node in depth-first preorder traversal, separated by "\n":
    • Depth-0 nodes (a user's very first action) format as f"{action} ({count})" with no indentation.
    • Depth-d nodes for d >= 1 begin with d space characters (" " * d), followed by "-> ", followed by f"{action} ({count})".
    • When logs is empty, return "".

Examples

Example 1

Input:
logs = [
    (20, 50, "cart"),
    (10, 30, "search"),
    (30, 15, "home"),
    (10, 10, "home"),
    (20, 20, "browse"),
    (30, 40, "search"),
    (10, 45, "item"),
    (30, 55, "search"),
    (10, 60, "pay"),
]

Output:
home (2)
 -> search (2)
  -> item (1)
   -> pay (1)
  -> search (1)
browse (1)
 -> cart (1)

Sorting each user's events by timestamp produces three timelines: - User 10: home -> search -> item -> pay - User 20: browse -> cart - User 30: home -> search -> search

Inserting in ascending ID order (10, 20, 30) creates root branch home first and browse second. Both users 10 and 30 traverse home -> search, so both nodes show (2). Under home -> search, user 10 creates child item before user 30 creates child search, so item (along with its child pay) prints ahead of the second search.

Example 2

Input:
logs = [
    (42, 100, "checkout"),
    (7, 50, "login"),
    (7, 50, "feed"),
]

Output:
login (1)
 -> feed (1)
checkout (1)

User 7 has two records tied at timestamp 50, so input order preserves login -> feed. Because users are inserted by ascending user_id, user 7's branch (login) is created before user 42's branch (checkout), even though user 42 appeared earlier in logs.

Example 3

Input:
logs = [(5, 250, "open")]

Output:
open (1)

A single record produces a single depth-0 line with no leading spaces or arrow.

Example 4

Input:
logs = [
    (3, 90, "watch"),
    (1, 10, "open"),
    (2, 20, "open"),
    (1, 25, "watch"),
    (3, 40, "open"),
    (3, 95, "bid"),
]

Output:
open (3)
 -> watch (2)
  -> bid (1)

Users 1, 2, and 3 all begin at open (3), users 1 and 3 continue to watch (2), and only user 3 reaches bid (1).

Constraints

  • 0 <= len(logs) <= 5 * 10^4
  • 1 <= user_id <= 10^9
  • 0 <= time <= 10^9
  • 1 <= len(action) <= 32; action contains printable non-whitespace ASCII characters.

Step-by-step walkthrough

  1. Restate the problem and output format

    We receive unordered log entries (user_id, time, action) and must summarize all user journeys as a formatted tree string:

    1. Per-user timeline: Group records by user_id and order each user's actions by time ascending. Whenever two records for the same user share the exact same time, keep their original relative order in logs.
    2. Deterministic insertion: Walk through users in ascending user_id order (10, then 20, then 30), inserting each user's action sequence into a prefix tree where each node counts how many distinct users reached that exact prefix.
    3. Repeated actions stay separate steps: home -> search -> search is three steps deep — the second search becomes a child underneath the first search.
    4. Preorder output: Print one ACTION (COUNT) line per node in depth-first preorder (depth leading spaces + "-> " for depth >= 1), keeping sibling nodes in the order they were first created. Empty input returns "".
  2. Why naive prefix tuples are slow and awkward

    A brute-force approach builds each user's action list sequence and slices every prefix tuple sequence[:1], sequence[:2], ..., sequence[:L], storing sets of user IDs in a flat dictionary {prefix_tuple: set_of_users}.

    That runs into two headaches: - Quadratic copying: Slicing sequence[:k] copies k strings at step k, so one user with L actions costs 1 + 2 + ... + L = O(L^2) work. - No tree structure: A flat dictionary remembers when each prefix was created, not which prefix is a child of which. In Example 1, home -> search -> search is created after root browse, yet in preorder it must print before root browse because it sits inside home's subtree.

  3. Key idea: share prefixes in a trie

    Instead of copying prefix slices, we store paths in a trie (prefix tree), where an invisible placeholder root branches into first actions (depth 0), each of those branches into second actions (depth 1), and so on:

    Example 1 trie (10 -> home,search,item,pay | 20 -> browse,cart | 30 -> home,search,search):
    
    (root)
      |-- home (count=2)               depth 0  [users 10, 30]
      |     `-- search (count=2)       depth 1  [users 10, 30]
      |           |-- item (count=1)   depth 2  [user 10, created 1st]
      |           |     `-- pay (1)    depth 3  [user 10]
      |           `-- search (count=1) depth 2  [user 30, created 2nd]
      `-- browse (count=1)             depth 0  [user 20]
            `-- cart (count=1)         depth 1  [user 20]
    

    Notice why we do not need a set of user IDs at each node! As we walk one user's journey from root, step 1 visits depth 0, step 2 visits depth 1, step 3 visits depth 2, and so on. Because depth strictly increases on every step, a single user can never visit the same trie node twice — even when repeating an action like search -> search (which visits depth 1 and then depth 2). Simply adding 1 to node.count at each step automatically counts distinct users!

  4. Phase 1: Group logs by user and keep input indices for ties

    In one pass over logs, we collect each user's events as (timestamp, input_index, action) tuples. When Python sorts tuples, it compares the first element (timestamp), and if two timestamps are equal it compares the second element (input_index). Because input_index (0, 1, 2, ...) is strictly unique, ties always stay in original input order and never fall through to comparing action alphabetically.

    def _group_logs_by_user(
        logs: List[Tuple[int, int, str]],
    ) -> Dict[int, List[Tuple[int, int, str]]]:
        """Group raw logs into {user_id: [(time, input_index, action), ...]}."""
        entries_by_user: Dict[int, List[Tuple[int, int, str]]] = {}
        for input_index, log in enumerate(logs):
            user_id, timestamp, action = log
            if user_id not in entries_by_user:
                entries_by_user[user_id] = []
            # Store input_index right after timestamp so equal timestamps keep input order.
            entries_by_user[user_id].append((timestamp, input_index, action))
        return entries_by_user
    
  5. Phase 2: Insert user journeys in ascending user_id order

    Each TrieNode holds count (starting at 0) and children (a plain Python dict mapping action -> TrieNode). Since Python 3.7+, dictionaries preserve the exact order keys were first inserted — which gives us "children in creation order" for free as long as we iterate over sorted(entries_by_user).

    class TrieNode:
        def __init__(self) -> None:
            # count: distinct users whose sorted journey passed through this exact prefix.
            self.count: int = 0
            # children: {action: child_node}; Python dicts keep insertion (= creation) order.
            self.children: Dict[str, "TrieNode"] = {}
    
    
    def _build_journey_trie(
        entries_by_user: Dict[int, List[Tuple[int, int, str]]],
    ) -> TrieNode:
        """Insert each user's chronological action path into a prefix tree."""
        root = TrieNode()
    
        # Process users in ascending user_id order so sibling creation order is deterministic.
        for user_id in sorted(entries_by_user):
            sorted_entries = sorted(entries_by_user[user_id])
            current_node = root
    
            for _timestamp, _input_index, action in sorted_entries:
                if action not in current_node.children:
                    current_node.children[action] = TrieNode()
                current_node = current_node.children[action]
                # One journey steps strictly deeper each time, so += 1 counts distinct users.
                current_node.count += 1
    
        return root
    
  6. Phase 3: Print in preorder with an explicit stack

    Depth-first preorder traversal prints a node first, then prints its first child's entire subtree, then its second child's entire subtree, and so on. Writing this recursively is tempting, but a single user with 5,000 actions creates a chain 5,000 nodes deep — crashing Python's ~1,000 recursion limit.

    Using an explicit list stack avoids any recursion limit. Because a stack is Last-In, First-Out, we push a node's children in reverse order so the earliest-created child sits on top and gets popped first:

    Suppose node search (depth 1) has children in creation order: [item, search_2]
      Push reversed: first push search_2, then push item  -->  stack top is item
      Pop item     -> print item, then push item's child pay -->  stack top is pay
      Pop pay      -> print pay (item's entire subtree is now finished!)
      Pop search_2 -> print search_2 next, in exact creation order!
    
    def _format_node_line(action: str, count: int, depth: int) -> str:
        """Format one tree node line, indenting non-root nodes by `depth` spaces before `-> `."""
        if depth == 0:
            return f"{action} ({count})"
        indent = " " * depth
        return f"{indent}-> {action} ({count})"
    
    
    def _render_preorder(root: TrieNode) -> str:
        """Render the trie in depth-first preorder using an explicit stack."""
        lines: List[str] = []
        # stack holds (action, node, depth); avoids Python's ~1000 recursion limit on long paths.
        stack: List[Tuple[str, TrieNode, int]] = []
    
        # Push children in reverse order so LIFO pop visits the earliest-created child first.
        root_children = list(root.children.items())
        for action, child_node in reversed(root_children):
            stack.append((action, child_node, 0))
    
        while stack:
            action, node, depth = stack.pop()
            lines.append(_format_node_line(action, node.count, depth))
    
            child_items = list(node.children.items())
            for child_action, child_node in reversed(child_items):
                stack.append((child_action, child_node, depth + 1))
    
        return "\n".join(lines)
    
    
    def build_summary(logs: List[Tuple[int, int, str]]) -> str:
        if not logs:
            return ""
        entries_by_user = _group_logs_by_user(logs)
        root = _build_journey_trie(entries_by_user)
        return _render_preorder(root)
    
  7. Full trace on Example 1

    Let's trace Example 1 from start to finish:

    1. Group & sort per user:
       user 10: (10, home), (30, search), (45, item), (60, pay) -> home -> search -> item -> pay
       user 20: (20, browse), (50, cart)                        -> browse -> cart
       user 30: (15, home), (40, search), (55, search)          -> home -> search -> search
    
    2. Insert in ascending user_id order (10, then 20, then 30):
       After 10: home(1) -> search(1) -> item(1) -> pay(1)
       After 20: root gets second child browse(1) -> cart(1)
       After 30: home becomes (2), home->search becomes (2), and home->search gets child search(1)
    
    3. Preorder output:
       home (2)
        -> search (2)
         -> item (1)
          -> pay (1)
         -> search (1)
       browse (1)
        -> cart (1)
    

    Notice that under home -> search, item (1) prints before search (1) because user 10 created item before user 30 created search.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TrieNode:
        def __init__(self) -> None:
            # count: distinct users whose sorted journey passed through this exact prefix.
            self.count: int = 0
            # children: {action: child_node}; Python dicts keep insertion (= creation) order.
            self.children: Dict[str, "TrieNode"] = {}
    
    
    def _group_logs_by_user(
        logs: List[Tuple[int, int, str]],
    ) -> Dict[int, List[Tuple[int, int, str]]]:
        """Group raw logs into {user_id: [(time, input_index, action), ...]}."""
        entries_by_user: Dict[int, List[Tuple[int, int, str]]] = {}
        for input_index, log in enumerate(logs):
            user_id, timestamp, action = log
            if user_id not in entries_by_user:
                entries_by_user[user_id] = []
            # Store input_index right after timestamp so equal timestamps keep input order.
            entries_by_user[user_id].append((timestamp, input_index, action))
        return entries_by_user
    
    
    def _build_journey_trie(
        entries_by_user: Dict[int, List[Tuple[int, int, str]]],
    ) -> TrieNode:
        """Insert each user's chronological action path into a prefix tree."""
        root = TrieNode()
    
        # Process users in ascending user_id order so sibling creation order is deterministic.
        for user_id in sorted(entries_by_user):
            sorted_entries = sorted(entries_by_user[user_id])
            current_node = root
    
            for _timestamp, _input_index, action in sorted_entries:
                if action not in current_node.children:
                    current_node.children[action] = TrieNode()
                current_node = current_node.children[action]
                # One journey steps strictly deeper each time, so += 1 counts distinct users.
                current_node.count += 1
    
        return root
    
    
    def _format_node_line(action: str, count: int, depth: int) -> str:
        """Format one tree node line, indenting non-root nodes by `depth` spaces before `-> `."""
        if depth == 0:
            return f"{action} ({count})"
        indent = " " * depth
        return f"{indent}-> {action} ({count})"
    
    
    def _render_preorder(root: TrieNode) -> str:
        """Render the trie in depth-first preorder using an explicit stack."""
        lines: List[str] = []
        # stack holds (action, node, depth); avoids Python's ~1000 recursion limit on long paths.
        stack: List[Tuple[str, TrieNode, int]] = []
    
        # Push children in reverse order so LIFO pop visits the earliest-created child first.
        root_children = list(root.children.items())
        for action, child_node in reversed(root_children):
            stack.append((action, child_node, 0))
    
        while stack:
            action, node, depth = stack.pop()
            lines.append(_format_node_line(action, node.count, depth))
    
            child_items = list(node.children.items())
            for child_action, child_node in reversed(child_items):
                stack.append((child_action, child_node, depth + 1))
    
        return "\n".join(lines)
    
    
    def build_summary(logs: List[Tuple[int, int, str]]) -> str:
        if not logs:
            return ""
        entries_by_user = _group_logs_by_user(logs)
        root = _build_journey_trie(entries_by_user)
        return _render_preorder(root)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture hikers entering a park gate and walking along trails marked by signposts (home, search, item, ...). Whenever two hikers start with the same sequence of turns — say home -> search — they walk down the exact same shared trunk from the gate, increasing that trail's visitor count by 1 per hiker; the moment one hiker turns toward item while another takes search again, a side trail branches off in the exact order hikers first carved it. In computer science, that shared branching structure is a trie (also called a prefix tree, a tree where each path from the root down to a node represents a shared prefix of sequences).

Why do simpler approaches break down? If you sort the entire log list globally by timestamp and insert actions as they arrive, different users' timelines interleave into one combined sequence instead of separate user funnels. And if you represent every prefix sequence[:k] as a tuple key in a flat dictionary, slicing all prefixes of an L-step journey copies 1 + 2 + ... + L = O(L^2) items and still lacks parent-child pointers to print subtrees in depth-first preorder traversal (visiting a parent node first, then completely printing each child's subtree in order before moving to the next sibling).

Let's trace three sorted user timelines — user 10: home -> search -> item, user 20: browse -> cart, and user 30: home -> search -> search:

Insert user 10 (home -> search -> item):   creates root -> home(1) -> search(1) -> item(1)
Insert user 20 (browse -> cart):           creates second root branch -> browse(1) -> cart(1)
Insert user 30 (home -> search -> search): reuses home(2) -> search(2), adds child search(1)

Preorder print (parent first, children in creation order):
  home (2)
   -> search (2)
    -> item (1)
    -> search (1)
  browse (1)
   -> cart (1)

Notice a subtle gift from the trie layout: we do not need to store a set of user IDs inside each node! Because step 1 of a user's journey always lands at depth 0, step 2 at depth 1, and step k at depth k - 1, one user's walk moves strictly downward and can never visit the same trie node twice — so incrementing node.count += 1 automatically counts distinct users.

Complexity

Let n be the total number of log entries, U (U <= n) be the number of distinct users, and S be the total character length of the formatted output string.

  • Time: O(n log n + S). Grouping logs by user_id scans the n logs once in O(n). Sorting user IDs takes O(U log U), and sorting each user's logs of size n_u sums across all users to sum(n_u log n_u) <= O(n log n). Inserting all sorted actions into the trie performs n O(1) dictionary lookups/updates, and iterative DFS visits at most n trie nodes while building S output characters (note S can reach O(n^2) spaces if one user takes n consecutive steps of depth 0..n-1).
  • Space: O(n + S). The grouped log lists store n tuples, the trie creates at most n TrieNode objects (at most one new node per log entry), the explicit DFS stack holds at most n tuples, and the final joined string occupies O(S) characters.

Edge cases

  • Empty input (logs = []): Returns "" immediately without printing a blank line or root node.
  • Single user with one action ([(5, 250, "open")]): Produces "open (1)" at depth 0 with no leading spaces or ->.
  • Equal timestamps for the same user: Storing (timestamp, input_index, action) acts as an explicit stable sort (a sort that preserves the original relative order of items with equal sort keys), so [(7, 50, "login"), (7, 50, "feed")] stays login -> feed.
  • Users appearing out of ID order in logs: Iterating for user_id in sorted(entries_by_user) ensures user 7 inserts before user 42 even if user 42 appeared earlier in logs, keeping sibling creation order deterministic.
  • Consecutive repeated actions (home -> home -> home): Each step advances current_node one level deeper, creating a 3-node chain home (1) -> -> home (1) -> -> home (1) rather than inflating a single node's count to 3.
  • Deep single-user journeys (5,000+ steps): Rendering uses an explicit Python list stack rather than recursive function calls, avoiding Python's call stack / recursion limit (the maximum number of nested function calls allowed before Python raises RecursionError, around 1,000 by default).

Common mistakes

  • Sorting all logs globally by time before grouping: That mixes actions from different users into one timeline instead of building separate per-user sequences first.
  • Sorting per-user tuples as (time, action): When two logs share the same timestamp, Python compares the next tuple element — sorting "feed" before "login" alphabetically instead of keeping original input order. Always put input_index between timestamp and action.
  • Iterating entries_by_user without sorted(...): Dictionary key order would follow the order users first appeared in logs instead of ascending user_id, printing siblings in the wrong order.
  • Pushing children onto the DFS stack in forward order: Because a stack pops Last-In-First-Out, pushing [item, search] pops search first! You must push reversed(...) so the first-created child item is popped first.
  • Deduplicating a user's actions with set or collapsing adjacent duplicates: Both destroy valid repeated steps like home -> search -> search.
  • Adding leading spaces to depth-0 root branches: Only nodes at depth >= 1 receive " " * depth + "-> ".

Alternative approaches

  • Prefix-tuple map with creation-path sorting: Map every prefix tuple sequence[:k] to (creation_id, set_of_users) and sort all prefixes by the tuple of creation_ids along their ancestor chain (id(p[:1]), id(p[:2]), ..., id(p)). That tuple key reproduces exact preorder traversal and makes a clean 20-line brute-force oracle in tests, at the cost of O(L^2) prefix slicing on long journeys.
  • Recursive DFS helper: A 6-line dfs(node, depth) function is completely natural when journeys are capped to a short funnel (e.g., at most 50 steps), though iterative stack DFS is safer for arbitrary log lengths.

Follow-up questions

  • How could you compute the exact number of users who exited right after each prefix without adding fields to the trie nodes? Every user who reaches node either takes a next action (contributing 1 to exactly one child of node) or ends their journey right at node. Therefore, exited = node.count - sum(child.count for child in node.children.values()) gives the exact exit count at that prefix with zero extra storage, and exited / node.count gives that step's drop-off rate.
  • What breaks if events arrive continuously from a live stream instead of a fixed batch, and how would you adapt the design? If events arrive strictly in chronological order per user, you only need a map {user_id: current_trie_node}: each new event advances that user one child down in O(1) time and increments the child's count! However, late out-of-order events can rewrite the middle of a user's sequence (requiring you to decrement counts along the old suffix and increment the new suffix), and ordering siblings by ascending-user_id creation order stops being meaningful on an unbounded stream, so live dashboards sort siblings by descending count or action name instead.
  • How would you scale this path summary to hundreds of millions of log records across a cluster of machines? Partition (shuffle) the raw logs by user_id so each worker receives all events for its subset of users, sorts each user's timeline locally, and emits (prefix_tuple, 1) up to a practical funnel depth cap K (such as the first K = 15 actions). Because each user emits any given prefix at most once, a distributed sum-by-key (SUM(1) grouped by prefix_tuple) computes exact distinct-user counts, and pruning rare prefixes (count < min_support) keeps the final rendered tree compact enough for analysts to read.

Follow-up questions

Similar questions

More Whatnot interview questions

All 21 Whatnot questions →