Analyze User Website Visit Pattern solution and explanation
9 more videos on this problem
LeetCode 1152. Analyze User Website Visit Pattern - Interview Prep Ep 109Fisher Coder · 19:37 · 15K views
1152. Analyze User Website Visit Pattern - Python LeetCode SolutionCode with Carter · 16:32 · 7K views
Leetcode 1152. Analyze User Website Visit Pattern | Heap | Sorting | Hasp Map | Amazon CodingNeedCode⚡ · 13:27 · 7K views
1152 Analyze User Website Visit Pattern (Biweekly Contest 6)Kelvin Chandra · 7:21 · 6K views
Amazon Coding Interview Question | Leetcode 1152 | Analyze User Website Visit PatternWorkWithGoogler · 27:33 · 6K views
LeetCode 1152. Analyze User Website Visit PatternKacy Codes · 18:18 · 3K views
🔥Leetcode 1152. Analyze User Website Visit Pattern - Python #amazon #microsoft #meta🏆AccelerateAI Careers · 14:19 · 2K views
LeetCode#1152 Analyze User Website Visit PatternOldYellowBricks · 15:36 · 1K views
Analyze User Website Visit PatternAmit K · 15:01 · 618 views
Leetcode 1152DailyLeetcode · 11:50 · 604 views
The 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 usersxsuch thatxvisited"home"then visited"away"and visited"love"after that. - Similarly, if the pattern is
["leetcode", "love", "leetcode"], the score is the number of usersxsuch thatxvisited"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 usersxsuch thatxvisited"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.
Example 1:
Input: username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"]
Output: ["home","about","career"]
Explanation: The tuples in this example are:
["joe","home",1],["joe","about",2],["joe","career",3],["james","home",4],["james","cart",5],["james","maps",6],["james","home",7],["mary","home",8],["mary","about",9], and ["mary","career",10].
The pattern ("home", "about", "career") has score 2 (joe and mary).
The pattern ("home", "cart", "maps") has score 1 (james).
The pattern ("home", "cart", "home") has score 1 (james).
The pattern ("home", "maps", "home") has score 1 (james).
The pattern ("cart", "maps", "home") has score 1 (james).
The pattern ("home", "home", "home") has score 0 (no user visited home 3 times).
Example 2:
Input: username = ["ua","ua","ua","ub","ub","ub"], timestamp = [1,2,3,4,5,6], website = ["a","b","a","a","b","c"] Output: ["a","b","a"]
Constraints:
3 <= username.length <= 501 <= username[i].length <= 10timestamp.length == username.length1 <= timestamp[i] <= 109website.length == username.length1 <= website[i].length <= 10username[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.
Approach overview
Problem Overview: Given parallel arrays username, timestamp, and website, determine the most common sequence of three websites visited by users in chronological order. Each user contributes at most one count per 3‑sequence, and ties are resolved using lexicographical order.
Approach 1: Brute Force Pattern Counting (O(n^4) time, O(n) space)
A naive method tries to generate every possible 3‑website sequence globally and checks how many users contain that sequence in order. For each candidate pattern, iterate through every user’s visit list and verify whether the sequence appears in chronological order. This involves nested iterations over websites and repeated scans of user histories. While straightforward, the repeated verification step makes the time complexity roughly O(n^4) in the worst case, so it quickly becomes impractical for larger inputs.
Approach 2: Hash Table + Sorting (O(n log n + c) time, O(n) space)
The efficient solution first sorts all visits by timestamp so each user’s browsing history is in chronological order. After sorting, build a hash map from user → list of visited websites. For each user, generate all possible combinations of three websites using three nested indices i < j < k. Store these patterns in a set to avoid counting duplicate patterns multiple times for the same user. Then update a global frequency map that counts how many users produced each 3‑sequence.
After processing all users, iterate through the frequency map to find the sequence with the highest count. If multiple patterns share the same frequency, choose the lexicographically smallest one. Sorting ensures correct visit order, and the hash table provides constant‑time updates when counting patterns. The overall cost is dominated by sorting O(n log n) plus generating combinations per user.
This approach relies heavily on sorting to maintain chronological order and hash tables for counting patterns efficiently. The input is stored in arrays, making iteration straightforward using basic array traversal.
Recommended for interviews: Interviewers expect the Hash Table + Sorting approach. Starting with a brute-force idea shows you understand the pattern search space, but optimizing with sorting and per‑user combination generation demonstrates strong problem‑solving skills and practical use of hash maps.
Solution
First, we use a hash table d to record the websites each user visits. Then we traverse d. For each user, we enumerate all the triplets they visited, count the occurrence of distinct triplets, and finally traverse all triplets, returning the one with the highest occurrence and the smallest lexicographic order.
The time complexity is O(n^3), and the space complexity is O(n^3). Here, n is the length of username.
class Solution:
def mostVisitedPattern(
self, username: List[str], timestamp: List[int], website: List[str]
) -> List[str]:
d = defaultdict(list)
for user, _, site in sorted(
zip(username, timestamp, website), key=lambda x: x[1]
):
d[user].append(site)
cnt = Counter()
for sites in d.values():
m = len(sites)
s = set()
if m > 2:
for i in range(m - 2):
for j in range(i + 1, m - 1):
for k in range(j + 1, m):
s.add((sites[i], sites[j], sites[k]))
for t in s:
cnt[t] += 1
return sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]class Solution {
public List<String> mostVisitedPattern(String[] username, int[] timestamp, String[] website) {
Map<String, List<Node>> d = new HashMap<>();
int n = username.length;
for (int i = 0; i < n; ++i) {
String user = username[i];
int ts = timestamp[i];
String site = website[i];
d.computeIfAbsent(user, k -> new ArrayList<>()).add(new Node(user, ts, site));
}
Map<String, Integer> cnt = new HashMap<>();
for (var sites : d.values()) {
int m = sites.size();
Set<String> s = new HashSet<>();
if (m > 2) {
Collections.sort(sites, (a, b) -> a.ts - b.ts);
for (int i = 0; i < m - 2; ++i) {
for (int j = i + 1; j < m - 1; ++j) {
for (int k = j + 1; k < m; ++k) {
s.add(sites.get(i).site + "," + sites.get(j).site + ","
+ sites.get(k).site);
}
}
}
}
for (String t : s) {
cnt.put(t, cnt.getOrDefault(t, 0) + 1);
}
}
int mx = 0;
String t = "";
for (var e : cnt.entrySet()) {
if (mx < e.getValue() || (mx == e.getValue() && e.getKey().compareTo(t) < 0)) {
mx = e.getValue();
t = e.getKey();
}
}
return Arrays.asList(t.split(","));
}
}
class Node {
String user;
int ts;
String site;
Node(String user, int ts, String site) {
this.user = user;
this.ts = ts;
this.site = site;
}
}class Solution {
public:
vector<string> mostVisitedPattern(vector<string>& username, vector<int>& timestamp, vector<string>& website) {
unordered_map<string, vector<pair<int, string>>> d;
int n = username.size();
for (int i = 0; i < n; ++i) {
auto user = username[i];
int ts = timestamp[i];
auto site = website[i];
d[user].emplace_back(ts, site);
}
unordered_map<string, int> cnt;
for (auto& [_, sites] : d) {
int m = sites.size();
unordered_set<string> s;
if (m > 2) {
sort(sites.begin(), sites.end());
for (int i = 0; i < m - 2; ++i) {
for (int j = i + 1; j < m - 1; ++j) {
for (int k = j + 1; k < m; ++k) {
s.insert(sites[i].second + "," + sites[j].second + "," + sites[k].second);
}
}
}
}
for (auto& t : s) {
cnt[t]++;
}
}
int mx = 0;
string t;
for (auto& [p, v] : cnt) {
if (mx < v || (mx == v && t > p)) {
mx = v;
t = p;
}
}
return split(t, ',');
}
vector<string> split(string& s, char c) {
vector<string> res;
stringstream ss(s);
string t;
while (getline(ss, t, c)) {
res.push_back(t);
}
return res;
}
};func mostVisitedPattern(username []string, timestamp []int, website []string) []string {
d := map[string][]pair{}
for i, user := range username {
ts := timestamp[i]
site := website[i]
d[user] = append(d[user], pair{ts, site})
}
cnt := map[string]int{}
for _, sites := range d {
m := len(sites)
s := map[string]bool{}
if m > 2 {
sort.Slice(sites, func(i, j int) bool { return sites[i].ts < sites[j].ts })
for i := 0; i < m-2; i++ {
for j := i + 1; j < m-1; j++ {
for k := j + 1; k < m; k++ {
s[sites[i].site+","+sites[j].site+","+sites[k].site] = true
}
}
}
}
for t := range s {
cnt[t]++
}
}
mx, t := 0, ""
for p, v := range cnt {
if mx < v || (mx == v && p < t) {
mx = v
t = p
}
}
return strings.Split(t, ",")
}
type pair struct {
ts int
site string
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Pattern Counting | O(n^4) | O(n) | Conceptual baseline or for explaining the search space of all 3‑website sequences. |
| Hash Table + Sorting | O(n log n + c) | O(n) | General case. Efficiently counts unique 3‑website patterns per user after sorting visits by time. |
Frequently asked questions
Is Analyze User Website Visit Pattern easy or hard?
Analyze User Website Visit Pattern is rated Medium on LeetCode. The challenge comes from combining multiple steps—sorting by timestamp, generating ordered combinations, deduplicating per user, and resolving lexicographical ties using hash maps.
Analyze User Website Visit Pattern Python/Java solution
Implement the optimized approach by sorting visits using timestamp, grouping websites per user with a dictionary or map, generating all 3‑website combinations, and counting them in a hash map. The same logic works across Python, Java, C++, and Go with minor syntax differences.
How to solve Analyze User Website Visit Pattern in O(n log n)?
Start by sorting all visits using the timestamp so each user’s browsing history is ordered. Build a map from username to a list of visited websites. For every user, generate all ordered triples (i < j < k) and record unique sequences using a set, then count them globally in a hash map. Finally, return the sequence with the highest frequency and smallest lexicographical order.
What is the best approach for Analyze User Website Visit Pattern?
The most efficient solution uses sorting and a hash table. First sort visits by timestamp, then group websites per user. Generate all 3‑website combinations for each user, store them in a set to avoid duplicates, and count frequencies using a hash map. The pattern with the highest frequency (and lexicographically smallest on ties) is the result.
Is Analyze User Website Visit Pattern asked at Google/Amazon/Meta?
Analyze User Website Visit Pattern is commonly associated with interview preparation for large tech companies, especially those that test hash maps and data analysis patterns. Variations of this problem have appeared in interview prep sets used by companies like Google, Amazon, and Meta.
What data structure is used in Analyze User Website Visit Pattern?
The key data structures are hash maps and sets. A hash map groups visits by username and tracks frequency of 3‑website patterns, while a set ensures each user contributes a pattern only once even if they visit the same sequence multiple times.
What is the time complexity of Analyze User Website Visit Pattern?
The optimal approach runs in O(n log n + c) time, where n is the number of visits and c is the number of generated 3‑website combinations across all users. The O(n log n) part comes from sorting by timestamp, while combination generation depends on how many visits each user has.
