Merge Per-User Action Sequences into a Counted Prefix Tree
Trees & GraphsAuto-graded · 19 test casesLast updated
Group event records by user, order each user's events by time, merge the sequences into a prefix tree with distinct-user counts, and print it in a fixed preorder format.
Counted Prefix Tree of User Sessions
You receive a list of event records, one per action a user performed. Each record is a triple (user_id, timestamp, action) with types (int, int, str). The records are in no particular order.
Write a function summarize_journeys(events) that returns a text rendering of a prefix tree built from every user's sequence of actions.
Building the sequences
- Collect all records belonging to the same user. Order that user's records by
timestamp, smallest first. The resulting list of actions is the user's journey. - If two records of one user share a timestamp, they keep the relative order in which they appeared in the input list. Do not break ties by action name.
Building the tree
- Every node represents an action reached by following a path of actions from the top. A path of actions from the top is a prefix.
- A node's count is the number of distinct users whose journey begins with exactly that prefix. Each user adds 1 to each prefix of their own journey, once.
- Matching is done only among the children of the current node. Repeating an action therefore goes one level deeper: the journey
A, B, Bproduces a nodeBunder the node forA, B, which is separate from the node forA, B. - Insert journeys in increasing
user_idorder. Children of a node are kept in the order in which they were first created during these insertions.
Output format
- Return one string with one line per node, lines joined by
"\n"(no trailing newline). - A line is
ACTION (COUNT), preceded by an indent when the node is not at the top level. - A node at depth
d(top-level nodes haved = 0) is prefixed withdspace characters followed by->whend > 0. Top-level nodes have no prefix. For example, depth 1 gives-> B (2)and depth 2 gives-> C (1). - Nodes are listed in depth-first preorder: a node, then its entire subtree child by child in creation order, then the next sibling.
- If
eventsis empty, return the empty string"".
Constraints
0 <= len(events) <= 10^5user_idandtimestampare integers;actionis a non-empty string.- A single journey can be long (up to the number of events), so avoid relying on deep recursion.
- The same action may appear several times in one journey.
Examples
Example 1
Input: summarize_journeys([[100, 1000, 'A'], [300, 1150, 'A'], [200, 1200, 'B'], [100, 1200, 'B'], [100, 1300, 'C'], [200, 1400, 'A'], [300, 1500, 'B'], [300, 1550, 'B'], [100, 1560, 'D']])
Output: 'A (2)\n -> B (2)\n -> C (1)\n -> D (1)\n -> B (1)\nB (1)\n -> A (1)'
Example 2
Input: summarize_journeys([])
Output: ''
Example 3
Input: summarize_journeys([[1, 100, 'X']])
Output: 'X (1)'
Example 4
Input: summarize_journeys([[1, 100, 'A'], [1, 200, 'B'], [2, 100, 'A'], [2, 200, 'B']])
Output: 'A (2)\n -> B (2)'
Hints
Hint 1
Group the records per user first, preserving input order inside each group, then sort each group by timestamp only. Python's sort is stable, so ties keep input order.
Hint 2
Treat each journey as a word and insert it into a trie. Look up the next action only among the children of the node you are currently at, so repeated actions create deeper nodes.
Hint 3
Process users in sorted user_id order and keep each node's children in a list (or insertion-ordered dict). For output use an explicit stack, pushing children in reverse so they pop in creation order, and indent with depth spaces plus '-> '.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each user's time-ordered list of actions can be seen as a word, and the whole task is to insert all words into a trie where every node counts how many words pass through it.
- Group by user. Walk through the records once and append
(timestamp, action)to a list per user, preserving input order. - Order each journey. Sort each user's list by timestamp only. Because Python's sort is stable, records with equal timestamps stay in input order, which is exactly the tie rule. Sorting by
(timestamp, action)would be wrong. - Insert into the trie. Go through users in ascending
user_id. For each action in the journey, look it up among the children of the current node. If it is missing, create it and append it to the node's ordered child list. Then increment the node's count and move into it. - Render. Do an iterative preorder traversal with a stack. Children are pushed in reverse so they are popped in creation order. Each line is
depthspaces, then->if depth is positive, thenACTION (COUNT).
Why it is correct
- A journey follows a single downward path, so it increments each prefix node on that path exactly once. The count of a node is therefore the number of distinct users whose journey starts with that prefix.
- Lookups only consider the current node's children, so a repeated action such as
A, B, Bcreates a new deeper node instead of merging with an ancestor. - Users are inserted in ascending id order and children are appended when first created, so the child order is fully determined. Preorder traversal then yields a deterministic output.
- An empty input yields no top-level nodes, and joining an empty list gives
"". - An explicit stack avoids recursion limits for very long journeys.
Complexity
With N events: grouping is O(N), sorting is O(N log N) overall (plus O(U log U) for the user ids, with U <= N), insertion is O(N) expected with hash lookups, and rendering is O(N) plus the output length. Total time is O(N log N). Space is O(N) for the groups, the tree, and the output lines.
Reference solution
from typing import List, Tuple
def summarize_journeys(events: List[Tuple[int, int, str]]) -> str:
# Group records per user, keeping input order within each user.
per_user = {}
for user_id, ts, action in events:
per_user.setdefault(user_id, []).append((ts, action))
top_nodes = []
top_index = {}
# Insert journeys in ascending user_id order.
for user_id in sorted(per_user):
index = top_index
sibling_list = top_nodes
# Stable sort on timestamp only, so ties keep input order.
journey = sorted(per_user[user_id], key=lambda rec: rec[0])
for _, action in journey:
node = index.get(action)
if node is None:
node = {"action": action, "count": 0, "children": [], "index": {}}
index[action] = node
sibling_list.append(node)
node["count"] += 1
sibling_list = node["children"]
index = node["index"]
# Iterative preorder traversal.
lines = []
stack = [(node, 0) for node in reversed(top_nodes)]
while stack:
node, depth = stack.pop()
indent = " " * depth + ("-> " if depth else "")
lines.append(f"{indent}{node['action']} ({node['count']})")
for child in reversed(node["children"]):
stack.append((child, depth + 1))
return "\n".join(lines)