KatInterview

Tally Opening Click-Paths Across Shoppers

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashinghash-mapgroupingsorting

Last 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], where user_id and action are strings and timestamp is an integer.
  • max_len: the largest opening-sequence length to count.

Output

Return a list of [sequence, count] pairs:

  • sequence is a list of action strings.
  • count is 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, login has the opening sequences ["login"] and ["login", "login"].
  • A user contributes at most once to any given sequence.

Constraints

  • 1 <= len(events) <= 10^5
  • 1 <= max_len <= 10
  • 1 <= len(user_id), len(action) <= 30
  • 0 <= 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.