Analyze User Website Visit Pattern
- 1 min read
- Array
- LC-Medium
Solution
- Zip all 3 lists together and sort by timestamp
- Make a adjacency list where key is username and value is list of websites visited in chronological order
- Iterate through 3-length combinations of each website and increment score for each pattern seen
- Iterate through scores and pick the pattern with the max score
| Time | Space | Explanation |
|---|
O() | O() | |
| | |
def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
visited = defaultdict(list)
for t, u, w in sorted(zip(timestamp, username, website)):
visited[u].append(w)
scores = defaultdict(lambda: 0)
for u, w in visited.items():
for pattern in set(combinations(w, 3)):
scores[pattern] += 1
max_score, best_pattern = 0, None
for p, s in scores.items():
if s > max_score or (s == max_score and p < best_pattern):
max_score, best_pattern = s, p
return best_pattern