Identify Most Popular Three-Page User Sequence
Arrays & HashingAuto-graded · 13 test casesLast updated
Process website activity logs to compute chronological 3-site visit subsequences and find the most widely performed pattern across unique users.
You are given website analytics data consisting of three parallel arrays: username, timestamp, and website. Each entry represents a visit to a specific page by a user at a given time point.
A 3-page visit sequence for a user is any ordered triple of web pages $(S_1, S_2, S_3)$ formed by three of that user's visits selected at indices $i < j < k$ after ordering all of that user's visits chronologically by timestamp. Note that the visits do not need to occur consecutively in time.
If a single user produces the exact same 3-page sequence through multiple different index combinations, that sequence is counted only once for that user.
Your objective is to find the 3-page sequence that is observed across the maximum number of distinct users. If there is a tie between multiple 3-page sequences with the highest user count, return the sequence that is lexicographically smallest.
If no user has at least 3 page visits, return an empty list [].
Format
The output should be a list of three strings representing the sequence [S1, S2, S3].
Constraints
- $n = \text{len(username)} = \text{len(timestamp)} = \text{len(website)}$
- $1 \le n \le 10,000$
- $1 \le \text{len(username[i])}, \text{len(website[i])} \le 10$
- All timestamps for a given user are unique.
Examples
Example 1
Input: find_most_common_pattern(['joe', 'joe', 'joe', 'james', 'james', 'james'], [1, 2, 3, 4, 5, 6], ['home', 'about', 'career', 'home', 'cart', 'books'])
Output: ['home', 'about', 'career']
Hints
Hint 1
Group page visits by username and sort each user's history by timestamp.
Hint 2
Generate all unique 3-element subsequences for each user using a set so that each sequence is counted at most once per user.
Hint 3
Use a hash map to aggregate how many unique users performed each 3-element sequence, then select the max-count sequence (using lexicographical order as a tie-breaker).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires us to aggregate website navigation sequences of length 3 across users and identify the single sequence performed by the highest number of distinct users.
-
Grouping and Sorting: Group the
(timestamp, website)logs byusername. For each user, sort their log entries in ascending order oftimestamp. This gives us a chronological sequence of page visits for every user. -
Subsequence Generation: For each user's sorted page list, generate all possible 3-page subsequences by choosing indices $i < j < k$. We store these subsequences in a
setfor that specific user. Using a set ensures that even if a user creates the sequence("home", "about", "home")multiple times via different timestamp combinations, it will only contribute $1$ to the total user count for that sequence. -
Global Counting & Tie-Breaking: Maintain a global frequency map counting how many unique users exhibited each 3-page sequence. After processing all users, find the maximum frequency. Filter for all sequences that achieve this maximum frequency and pick the lexicographically smallest tuple using standard tuple comparison.
Complexity
- Time Complexity: $\mathcal{O}(n \log n + \sum \binom{k_u}{3})$, where $n$ is the total number of log entries and $k_u$ is the number of visits by user $u$. Sorting takes $\mathcal{O}(n \log n)$ overall, and generating combinations per user takes cubic time in the user's visit length. For small or typical per-user visit counts, this executes well within time limits.
- Space Complexity: $\mathcal{O}(n + P)$ where $P$ is the total number of unique 3-page sequences tracked in memory across all users.
Python Reference Solution
from collections import defaultdict
from itertools import combinations
from typing import List
def find_most_common_pattern(username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
# Group visits by user
user_visits = defaultdict(list)
for u, t, w in zip(username, timestamp, website):
user_visits[u].append((t, w))
# Track pattern occurrences across distinct users
pattern_user_counts = defaultdict(int)
for u, visits in user_visits.items():
# Sort chronologically by timestamp
visits.sort(key=lambda x: x[0])
sites = [w for t, w in visits]
# Collect distinct 3-page subsequences for this user
unique_patterns_for_user = set()
for idx_triple in combinations(range(len(sites)), 3):
seq = tuple(sites[i] for i in idx_triple)
unique_patterns_for_user.add(seq)
for seq in unique_patterns_for_user:
pattern_user_counts[seq] += 1
if not pattern_user_counts:
return []
# Find sequence with max unique user count; break ties lexicographically
max_count = max(pattern_user_counts.values())
candidates = [seq for seq, cnt in pattern_user_counts.items() if cnt == max_count]
return list(min(candidates))