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:
- Chronological per-user timelines: Separate events by
user_idand order each user's events by ascendingtime. Whenever two events belonging to the same user have identicaltimevalues, keep them in the relative order in which they appeared inlogs. - Prefix tree construction: Insert user timelines into a prefix tree one user at a time in strictly ascending
user_idorder. 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. - 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 depth0,"search"at depth1, and a separate child"search"beneath it at depth2. A single user adds1to each visited node's user count. - 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_idinsertion pass. - Text rendering: Output one line per tree node in depth-first preorder traversal, separated by
"\n":- Depth-
0nodes (a user's very first action) format asf"{action} ({count})"with no indentation. - Depth-
dnodes ford >= 1begin withdspace characters (" " * d), followed by"-> ", followed byf"{action} ({count})". - When
logsis empty, return"".
- Depth-
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^41 <= user_id <= 10^90 <= time <= 10^91 <= len(action) <= 32;actioncontains printable non-whitespace ASCII characters.
Step-by-step walkthrough
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:- Per-user timeline: Group records by
user_idand order each user's actions bytimeascending. Whenever two records for the same user share the exact sametime, keep their original relative order inlogs. - Deterministic insertion: Walk through users in ascending
user_idorder (10, then20, then30), inserting each user's action sequence into a prefix tree where each node counts how many distinct users reached that exact prefix. - Repeated actions stay separate steps:
home -> search -> searchis three steps deep — the secondsearchbecomes a child underneath the firstsearch. - Preorder output: Print one
ACTION (COUNT)line per node in depth-first preorder (depthleading spaces +"-> "fordepth >= 1), keeping sibling nodes in the order they were first created. Empty input returns"".
- Per-user timeline: Group records by
Why naive prefix tuples are slow and awkward
A brute-force approach builds each user's action list
sequenceand slices every prefix tuplesequence[: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]copieskstrings at stepk, so one user withLactions costs1 + 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 -> searchis created after rootbrowse, yet in preorder it must print before rootbrowsebecause it sits insidehome's subtree.Key idea: share prefixes in a trie
Instead of copying prefix slices, we store paths in a trie (prefix tree), where an invisible placeholder
rootbranches into first actions (depth0), each of those branches into second actions (depth1), 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
setof user IDs at each node! As we walk one user's journey fromroot, step 1 visits depth0, step 2 visits depth1, step 3 visits depth2, 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 likesearch -> search(which visits depth1and then depth2). Simply adding1tonode.countat each step automatically counts distinct users!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). Becauseinput_index(0, 1, 2, ...) is strictly unique, ties always stay in original input order and never fall through to comparingactionalphabetically.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_userPhase 2: Insert user journeys in ascending user_id order
Each
TrieNodeholdscount(starting at0) andchildren(a plain Pythondictmappingaction -> 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 oversorted(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 rootPhase 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,000actions creates a chain5,000nodes deep — crashing Python's ~1,000recursion limit.Using an explicit list
stackavoids 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)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 beforesearch (1)because user10createditembefore user30createdsearch.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 byuser_idscans thenlogs once inO(n). Sorting user IDs takesO(U log U), and sorting each user's logs of sizen_usums across all users tosum(n_u log n_u) <= O(n log n). Inserting all sorted actions into the trie performsnO(1)dictionary lookups/updates, and iterative DFS visits at mostntrie nodes while buildingSoutput characters (noteScan reachO(n^2)spaces if one user takesnconsecutive steps of depth0..n-1). - Space:
O(n + S). The grouped log lists storentuples, the trie creates at mostnTrieNodeobjects (at most one new node per log entry), the explicit DFS stack holds at mostntuples, and the final joined string occupiesO(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 depth0with 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")]stayslogin -> feed. - Users appearing out of ID order in
logs: Iteratingfor user_id in sorted(entries_by_user)ensures user7inserts before user42even if user42appeared earlier inlogs, keeping sibling creation order deterministic. - Consecutive repeated actions (
home -> home -> home): Each step advancescurrent_nodeone level deeper, creating a 3-node chainhome (1)->-> home (1)->-> home (1)rather than inflating a single node's count to3. - 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 raisesRecursionError, around1,000by default).
Common mistakes
- Sorting all logs globally by
timebefore 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 putinput_indexbetweentimestampandaction. - Iterating
entries_by_userwithoutsorted(...): Dictionary key order would follow the order users first appeared inlogsinstead of ascendinguser_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]popssearchfirst! You must pushreversed(...)so the first-created childitemis popped first. - Deduplicating a user's actions with
setor collapsing adjacent duplicates: Both destroy valid repeated steps likehome -> search -> search. - Adding leading spaces to depth-
0root branches: Only nodes atdepth >= 1receive" " * 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 ofcreation_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 ofO(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 most50steps), 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
nodeeither takes a next action (contributing1to exactly one child ofnode) or ends their journey right atnode. 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, andexited / node.countgives 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 inO(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_idcreation order stops being meaningful on an unbounded stream, so live dashboards sort siblings by descendingcountor 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_idso 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 capK(such as the firstK = 15actions). Because each user emits any given prefix at most once, a distributed sum-by-key (SUM(1)grouped byprefix_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
- How could you compute the exact number of users who exited right after each prefix without adding fields to the trie nodes?
- What breaks if events arrive continuously from a live stream instead of a fixed batch, and how would you adapt the design?
- How would you scale this path summary to hundreds of millions of log records across a cluster of machines?
Similar questions
- Stateful Tic-Tac-Toe Engine and Mobile View
- Valid Palindrome With One Optional Deletion
- Banned Phrase Chat Filter
- User Activity Prefix Counts
- Efficient Dot Product for Sparse Vectors
- Valid Keypad Sequences Under Knight Moves
More Whatnot interview questions
- Valid Palindrome With One Optional Deletion Easy
- Valid Keypad Sequences Under Knight Moves Medium
- Stateful Tic-Tac-Toe Engine and Mobile View Medium Pro
- Live-Shopping Trending Stream Discovery Medium Pro
- Efficient Dot Product for Sparse Vectors Medium Pro
- Evaluate and Debug a Live-Shopping Marketplace App Medium Pro
- Month-over-Month Customer Retention Medium Pro
- Calendar-Aware 7-Day Moving Average in SQL Medium Pro
- Banned Phrase Chat Filter Medium Pro
- User Activity Prefix Counts Easy Pro