Most Popular Three-Page Browsing Path Across Users
Arrays & HashingAuto-graded · 23 test casesLast updated
Group visit logs by user, order them by time, and find the three-page ordered path shared by the most distinct users, with a lexicographic tie-break.
A site keeps a log of page views. You get three lists of the same length: user_ids, times and pages. Entry i means that user user_ids[i] opened page pages[i] at time times[i]. The entries are in arbitrary order.
A path is an ordered triple of page names. Repeated names are allowed, so ["home", "home", "cart"] is a valid path.
For each user, sort their views by time. If two of a user's views have the same time, the one with the lexicographically smaller page name comes first. A user walks a path if the path's three pages can be picked from the user's sorted views at three increasing positions, in the same order as the path. The picked views need not be adjacent. If the same triple can be picked in several ways, the user still counts only once for that path.
The popularity of a path is the number of distinct users who walk it.
Return the path with the highest popularity as a list of three strings. If several paths tie, return the lexicographically smallest one, comparing the first page names, then the second, then the third. If no user has at least three views, return an empty list.
Constraints
user_ids,timesandpageshave the same lengthn, andnmay be 0.- Each
user_ids[i]andpages[i]is a string. Eachtimes[i]is an integer. - A user may have several views with the same time. Break those ties by page name ascending, as described above.
- Page names are compared as ordinary Python strings.
- The result is a list of exactly three strings, or
[]when no path exists.
Examples
Example 1
Input: top_three_page_path(['u1', 'u2', 'u1', 'u1', 'u2', 'u2'], [1, 1, 2, 3, 2, 3], ['home', 'home', 'cart', 'checkout', 'cart', 'checkout'])
Output: ['home', 'cart', 'checkout']
Example 2
Input: top_three_page_path(['u1', 'u1', 'u1', 'u2', 'u2', 'u2'], [1, 2, 3, 1, 2, 3], ['a', 'b', 'c', 'a', 'b', 'c'])
Output: ['a', 'b', 'c']
Example 3
Input: top_three_page_path(['u1', 'u1', 'u1', 'u1'], [4, 1, 3, 2], ['d', 'a', 'c', 'b'])
Output: ['a', 'b', 'c']
Hints
Hint 1
Group the views by user first, then sort each user's views by (time, page name) so the order is fully determined.
Hint 2
For one user, collect every ordered triple of pages taken from increasing positions into a set, so a user adds at most 1 to any path.
Hint 3
Keep one global counter over paths. After processing all users, take the maximum count and, among the paths with that count, the smallest one under tuple comparison.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Group the views by user.
- Sort each user's views by
(time, page). This makes the order well defined even when times are equal. - For each user, build the set of all ordered triples that can be picked at increasing positions in the sorted page list. Using a set means each user contributes at most once to any path.
- Add each user's set to one global counter, so the counter holds the number of distinct users per path.
- If the counter is empty, no user had three views, so return
[]. - Otherwise find the maximum count and return the smallest path (tuple comparison) among the paths that reach it.
Why it is correct
Every valid (user, path) pair appears exactly once, because each user's triples are deduplicated before counting. The counter value is therefore exactly the number of distinct users who walk the path. The sort key gives a deterministic order for equal timestamps. Tuple comparison on page names is the required lexicographic order for ties.
Complexity
Let n be the number of records and m_u the number of views for user u.
- Sorting and grouping take
O(n log n). - Generating triples for a user takes
O(m_u^3)in the worst case, and the total isO(sum m_u^3). This is worst when one user holds most of the records, givingO(n^3). Spreading the same records across many users with short histories makes this term much smaller. - The number of distinct paths is at most
min(sum C(m_u, 3), V^3), whereVis the number of distinct page names. - Memory is
O(n + P), wherePis the number of distinct paths stored in the counter, plus the per-user set while it is being built. - Choosing the winner takes
O(P)comparisons.
If one user's history is much longer than the number of distinct pages they visit, the per-user step can be made to depend on distinct pages rather than visit count. For example, you can track for each prefix pair whether it has been seen. That costs more code, and it only pays off when histories are long and repetitive.
Reference solution
from collections import Counter, defaultdict
from itertools import combinations
from typing import List
def top_three_page_path(user_ids: List[str], times: List[int], pages: List[str]) -> List[str]:
views = defaultdict(list)
for user, t, page in zip(user_ids, times, pages):
views[user].append((t, page))
popularity = Counter()
for user_views in views.values():
user_views.sort(key=lambda v: (v[0], v[1]))
names = [page for _, page in user_views]
paths = set(combinations(names, 3))
popularity.update(paths)
if not popularity:
return []
best = max(popularity.values())
return list(min(path for path, count in popularity.items() if count == best))