Tally Opening Click-Paths Across Shoppers
Arrays & HashingAuto-graded · 19 test casesLast updated
Group timestamped events by user, order them in time, and count how many distinct users share each opening action sequence of length up to k.
Opening Click-Paths
A shopping site records every user interaction as a record [user_id, timestamp, action]. The records arrive in arbitrary order, with different users interleaved.
For each user, the path is the list of that user's actions ordered by increasing timestamp. A opening sequence of length L is the first L actions of a path.
Given the records and an integer max_len, determine, for every opening sequence of length 1 through max_len, how many different users have that sequence as the start of their path. A user whose path has fewer than max_len actions contributes only opening sequences up to the length of their path.
Input
events: a list of records[user_id, timestamp, action], whereuser_idandactionare strings andtimestampis an integer.max_len: the largest opening-sequence length to count.
Output
Return a list of [sequence, count] pairs:
sequenceis a list of action strings.countis the number of distinct users whose path begins with that sequence.- Include only sequences with a count of at least 1.
- Sort the pairs in ascending lexicographic order of
sequence, comparing element by element as strings. A sequence that is a proper prefix of another comes before it.
If max_len <= 0, return an empty list.
Notes
- Repeated actions in a path are kept. The path
login, loginhas the opening sequences["login"]and["login", "login"]. - A user contributes at most once to any given sequence.
Constraints
1 <= len(events) <= 10^51 <= max_len <= 101 <= len(user_id), len(action) <= 300 <= timestamp <= 10^9- Every
(user_id, timestamp)pair is unique.
Examples
Example 1
Input: tally_journey_prefixes([['u1', 100, 'home'], ['u2', 90, 'home'], ['u1', 110, 'item'], ['u1', 105, 'search'], ['u2', 95, 'search'], ['u2', 120, 'cart'], ['u3', 50, 'stream']], 2)
Output: [[['home'], 2], [['home', 'search'], 2], [['stream'], 1]]
Example 2
Input: tally_journey_prefixes([['u1', 10, 'login'], ['u1', 20, 'login']], 3)
Output: [[['login'], 1], [['login', 'login'], 1]]
Hints
Hint 1
Start by collecting each user's (timestamp, action) pairs in a dictionary keyed by user_id, since the input order is arbitrary.
Hint 2
After sorting a user's pairs by timestamp, you only need the first max_len actions. Build the opening sequence incrementally and bump a counter after each added action.
Hint 3
Lists cannot be dictionary keys, so use tuples as keys. A single user creates exactly one sequence per length, so no extra de-duplication is needed. Sort the keys at the end and convert them to lists.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Group by user. Build a dictionary mapping each
user_idto its list of(timestamp, action)pairs. This handles interleaved, unordered input. - Order each path. Sort each user's pairs by timestamp. Because
(user_id, timestamp)pairs are unique, the order is unambiguous. - Count opening sequences. Walk the first
max_lenactions of the sorted path, appending each to a running list. After each append, increment the counter fortuple(running_list). - Format the output. Sort the tuple keys, which Python compares lexicographically so that shorter prefixes come before their extensions, and emit
[list(sequence), count]pairs.
Why it is correct
- A user produces exactly one sequence of each length, and sequences of different lengths are different tuples. So a user never increments the same key twice, and a plain
+= 1counts distinct users. - Slicing with
[:max_len]stops at eithermax_lenor the path length, whichever is smaller, which matches the required bound. - Repeated actions are handled naturally because position is part of the tuple.
- Tuples are hashable, which lists are not, so they serve as dictionary keys.
Complexity
Let n = len(events) and P be the number of distinct sequences (at most n * max_len).
- Grouping is O(n).
- Sorting is O(n log n) in the worst case, when one user owns all events.
- Building tuple keys costs O(n * max_len) in total.
- The final sort costs O(P * max_len * log P), since each comparison can take up to O(max_len).
Time: O(n log n + n * max_len + P * max_len * log P). Space: O(n + P * max_len).
Reference solution
from collections import defaultdict
from typing import List
def tally_journey_prefixes(events: List[List[object]], max_len: int) -> List[List[object]]:
if max_len <= 0:
return []
paths = defaultdict(list)
for user_id, timestamp, action in events:
paths[user_id].append((timestamp, action))
counts = defaultdict(int)
for items in paths.values():
items.sort(key=lambda pair: pair[0])
current = []
for _, action in items[:max_len]:
current.append(action)
counts[tuple(current)] += 1
return [[list(seq), counts[seq]] for seq in sorted(counts)]