[
hash table
string
]
Leetcode 1152 Analyze User Website Visit Pattern
Problem statement
https://leetcode.com/problems/analyze-user-website-visit-pattern/
Solution
What we need to do is to create hash table user_sites
where for each user we keep visited sites. Then we create counter patterns
, and traverse each triple of sites for each user.
Complexity
Time complexity can be potentially upto O(N^3)
to generate all triplets, space complexity is also can be O(N^3)
.
Code
class Solution:
def mostVisitedPattern(self, username, timestamp, website):
user_sites = defaultdict(list)
for u, t, w in zip(username, timestamp, website):
user_sites[u].append((t, w))
patterns = defaultdict(set)
for user in user_sites:
for x, y, z in combinations(sorted(user_sites[user]), 3):
patterns[x[1], y[1], z[1]].add(user)
max_freq = max(len(f) for f in patterns.values())
return min(x for x in patterns if len(patterns[x]) == max_freq)