- Interview Questions
- /
- Problems
- /
- Analyze User Website Visit Pattern
Analyze User Website Visit Pattern
Find the ordered sequence of three websites that the most users visited, in order, at some point. Tests grouping by user, enumerating ordered triples, and counting each user once per pattern. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given three arrays of the same length describing a visit log: username[i] visited website[i] at time timestamp[i]. The rows are not sorted by time.
A pattern is an ordered list of three websites, like ["home", "shop", "cart"]. The websites don't have to be different. A user follows a pattern if, looking at that user's visits in time order, they visited the first website, then later the second, then later the third. The three visits don't have to be back to back; other visits can happen in between.
The score of a pattern is the number of distinct users who follow it. A user who follows a pattern in several ways still adds only 1.
Return the pattern with the highest score. If several patterns tie, return the lexicographically smallest one: compare the first websites as strings, then the second, then the third. At least one user has three or more visits, so an answer always exists.
Example 1
- Input
- username = ["ann", "ann", "ann", "bo", "bo", "bo", "bo", "cy", "cy", "cy"] timestamp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] website = ["home", "shop", "cart", "home", "news", "shop", "cart", "home", "shop", "cart"]
- Output
- ["home", "shop", "cart"]
All three users follow home, shop, cart. For bo the "news" visit in the middle doesn't break the pattern. No other pattern reaches a score of 3.
Example 2
- Input
- username = ["kim", "lee", "kim", "lee", "kim", "lee"] timestamp = [5, 2, 1, 9, 3, 4] website = ["z", "b", "x", "c", "y", "a"]
- Output
- ["b", "a", "c"]
Sorted by time, kim visits x, y, z and lee visits b, a, c. Both patterns score 1, and ["b", "a", "c"] is smaller because "b" < "x".
Example 3
- Input
- username = ["p", "p", "p", "p", "p", "p", "q", "q", "q", "r", "r", "r"] timestamp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] website = ["a", "b", "c", "a", "b", "c", "c", "b", "a", "c", "b", "a"]
- Output
- ["c", "b", "a"]
p follows a, b, c in four different ways, but that still counts as one user, so its score is 1. q and r both follow c, b, a for a score of 2.
Constraints
- 3 ≤ username.length ≤ 1000
- username.length == timestamp.length == website.length
- 1 ≤ username[i].length, website[i].length ≤ 10, lowercase letters and digits
- 1 ≤ timestamp[i] ≤ 10⁹, and all timestamps are distinct.
- At least one user has three or more visits.
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Analyze User Website Visit Pattern in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Analyze User Website Visit Pattern
Pattern: Group, enumerate triples, count with a set per user
Break it into three steps you already know:
- Order and group. Sort the rows by timestamp, then build each user's list of websites in time order.
- Enumerate. For each user, every choice of indices
i < j < kin their list gives a pattern they follow. Put these into a set first, so a user who follows the same pattern several ways contributes it once. - Count and pick. Add 1 to a global counter for each pattern in the user's set. At the end, take the highest count, breaking ties by the smallest pattern.
The set per user is the detail that makes or breaks the problem. Without it, one user who loops through the same pages repeatedly can outvote several real users.
Approach 1: Try every candidate pattern against every user
Collect every pattern any user follows, then for each candidate scan every user's sequence with a three-pointer subsequence check. It is correct, but with P candidate patterns and L total visits the work is roughly P · L, which grows fast.
Time O(P · L) · Space O(P)
Approach 2: Per-user triple sets with a global counter
- Sort row indices by timestamp and append each website to its user's list.
- For each user with list length m, loop
i < j < kand add(w[i], w[j], w[k])to a local set. - For each pattern in the set, increment
count[pattern]. - Return the pattern with the largest count, using the smaller pattern on ties.
Time O(L log L + Σ mᵤ³) · Space O(Σ mᵤ³) for the patterns
| Approach | Time | Space |
|---|---|---|
| Try every candidate pattern against every user | O(P · L) | O(P) |
| Per-user triple sets with a global counter | O(L log L + Σ mᵤ³) | O(Σ mᵤ³) for the patterns |
Solution code
Try the practice editor first. Both solutions pass every test above.
Analyze User Website Visit Pattern solution in Python
def most_visited_pattern(username: list[str], timestamp: list[int], website: list[str]) -> list[str]:
visits = defaultdict(list) # user -> websites in time order
for _, user, site in sorted(zip(timestamp, username, website)):
visits[user].append(site)
count = Counter()
for sites in visits.values():
count.update(set(itertools.combinations(sites, 3)))
best = max(count.values())
return list(min(p for p, c in count.items() if c == best))Analyze User Website Visit Pattern solution in JavaScript
function mostVisitedPattern(username, timestamp, website) {
const order = username.map((_, i) => i).sort((a, b) => timestamp[a] - timestamp[b]);
const visits = new Map(); // user -> websites in time order
for (const i of order) {
if (!visits.has(username[i])) visits.set(username[i], []);
visits.get(username[i]).push(website[i]);
}
const count = new Map(); // JSON-encoded pattern -> number of users
for (const sites of visits.values()) {
const seen = new Set();
for (let i = 0; i < sites.length; i++) {
for (let j = i + 1; j < sites.length; j++) {
for (let k = j + 1; k < sites.length; k++) {
seen.add(JSON.stringify([sites[i], sites[j], sites[k]]));
}
}
}
for (const key of seen) count.set(key, (count.get(key) || 0) + 1);
}
const smaller = (a, b) => {
for (let i = 0; i < 3; i++) {
if (a[i] !== b[i]) return a[i] < b[i];
}
return false;
};
let best = null;
let bestCount = 0;
for (const [key, c] of count) {
const pattern = JSON.parse(key);
if (c > bestCount || (c === bestCount && smaller(pattern, best))) {
best = pattern;
bestCount = c;
}
}
return best;
}Common mistakes
- Counting a pattern once per occurrence instead of once per user. Deduplicate with a set for each user first.
- Forgetting to sort by timestamp. The input rows are not in time order.
- Requiring the three visits to be consecutive. Any increasing choice of positions counts.
- Breaking ties by comparing patterns joined with a separator that sorts after letters, or by insertion order. Compare website by website.
- Assuming the three websites must be different. A user who visits the same page three times follows ["x", "x", "x"].
What interviewers look for
Ask the clarifying questions first: can websites repeat in a pattern, do the visits need to be consecutive, and how ties are broken. Interviewers often ask this problem mainly to see whether you pin those down.
Then say the cost honestly. The triple enumeration is cubic in the number of visits per user, which is fine because individual users have few visits, but call it out and mention that the per-user set is what keeps counts correct.
Follow-up questions
What if one user has thousands of visits?
Cubic enumeration blows up for that user. If the number of distinct websites W is small, enumerate the W³ candidate patterns instead and check each with a linear subsequence scan, or precompute next-occurrence tables so each check is O(1) per step.
How would you generalize to patterns of length k?
Generate all length-k subsequences per user with recursion or itertools.combinations, still deduplicated per user. The cost is C(m, k) per user, so it only works for small k and short histories.
What if the log is too big for one machine?
Shard by username so each user's visits land on one worker, sort and enumerate locally, and emit (pattern, 1) per distinct pattern per user. A second reduce step sums counts by pattern and keeps the best one with the tie-break rule.
Companies that ask Analyze User Website Visit Pattern
Analyze User Website Visit Pattern is tagged by 95 companies in our interview dataset. The score shows how often it comes up at each company.
- Wex100%
- Unacademy100%
- Activtrak100%
- T-Mobile100%
- Tempus100%
- Everbridge93%
- Bear Robotics93%
- Swiss Re92%
- Biontech91%
- Applied Materials87%
- Booz Allen Hamilton87%
- Spotify86.3%
- Yext84%
- Discord83%
- Panasonic83%
- Avanade82%
- Lumentum81%
- Hinge81%
- Rally Health80%
- Wepay80%
- Charles Schwab80%
- Carbon Health80%
- Liveperson78%
- Whatnot78%
and 71 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required