Problem
You are given two string arrays username
and website
and an integer array timestamp
. All the given arrays are of the same length and the tuple
[username[i], website[i], timestamp[i]]
indicates that the user username[i]
visited the website website[i]
at time timestamp[i]
.
A pattern is a list of three websites (not necessarily distinct).
- For example,
["home", "away", "love"]
,["leetcode", "love", "leetcode"]
, and["luffy", "luffy", "luffy"]
are all patterns.
The score of a pattern is the number of users that visited all the websites in the pattern in the same order they appeared in the pattern.
- For example, if the pattern is
["home", "away", "love"]
, the score is the number of usersx
such thatx
visited"home"
then visited"away"
and visited"love"
after that. - Similarly, if the pattern is
["leetcode", "love", "leetcode"]
, the score is the number of usersx
such thatx
visited"leetcode"
then visited"love"
and visited"leetcode"
one more time after that. - Also, if the pattern is
["luffy", "luffy", "luffy"]
, the score is the number of usersx
such thatx
visited"luffy"
three different times at different timestamps.
Return the pattern with the largest score. If there is more than one pattern with the same largest score, return the lexicographically smallest such pattern.
Note that the websites in a pattern do not need to be visited contiguously , they only need to be visited in the order they appeared in the pattern.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
3 <= username.length <= 50
1 <= username[i].length <= 10
timestamp.length == username.length
1 <= timestamp[i] <= 10^9
website.length == username.length
1 <= website[i].length <= 10
username[i]
andwebsite[i]
consist of lowercase English letters.- It is guaranteed that there is at least one user who visited at least three websites.
- All the tuples
[username[i], timestamp[i], website[i]]
are unique.
Solution
Method 1 - Brute Force with Hash Map
Intuition: We want to find the 3-website pattern visited in order by the largest number of users. For each user, we can generate all possible 3-sequences of their website visits, then count how many users have each pattern.
Approach:
- Combine the input arrays into a list of (username, timestamp, website) tuples and sort by timestamp.
- For each user, collect their website visit order.
- For each user, generate all unique 3-sequences (patterns) from their visit order.
- Use a map to count how many unique users have each pattern.
- Return the lexicographically smallest pattern with the highest user count.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity: O(U * W^3), where U is the number of users and W is the max number of websites visited by a user (since we generate all 3-sequences per user).
- 🧺 Space complexity: O(P + N), where P is the number of unique patterns and N is the input size.