KatInterview

Most Popular Three-Page Browsing Path Across Users

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinghashingsortingcombinations

Last 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, times and pages have the same length n, and n may be 0.
  • Each user_ids[i] and pages[i] is a string. Each times[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.