NeetCode #101LC-1152MediumArrays & Hashing
← Back to All Problems#101 · #1152 · Analyze User Website Visit Pattern(用户网站访问行为分析)
📌 Problem Statement & Constraints
Given arrays
username, timestamp and website describing visits, find the pattern (an ordered triple of websites) visited by the most users. Ties are broken by choosing the lexicographically smallest pattern. Constraints: 3 <= username.length <= 50, timestamps are distinct, each user visits at least 3 distinct websites.💡 Core Algorithmic Approaches
- Group visits by user and sort each user's visits by timestamp to obtain the chronological website sequence.
- For each user, take the set of all 3-element combinations (subsequences, not necessarily contiguous) of their visit sequence -- the set removes duplicate patterns from the same user, since a pattern counts each user only once.
- Count how many users produced each pattern.
- Pick the pattern with the highest count; ties are broken by lexicographic order, which
minover tuples gives for free.
💻 Benchmark Python3 Implementation
class Solution:
def mostVisitedPattern(self, username: List[str], timestamp: List[int],
website: List[str]) -> List[str]:
from collections import defaultdict
from itertools import combinations
visits = defaultdict(list)
for u, t, w in sorted(zip(username, timestamp, website), key=lambda x: x[1]):
visits[u].append(w) # chronological per user
cnt = defaultdict(int)
for sites in visits.values():
for combo in set(combinations(sites, 3)): # set: one vote per user
cnt[combo] += 1
best = max(cnt.values())
return list(min(k for k, v in cnt.items() if v == best))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log n + U * L^3) where U is the number of users and L the visits per user. Sorting dominates for typical inputs; the combination enumeration is bounded by 50 choose 3.
💾 Space Complexity
O(n) for the grouping and the pattern counter.
⚠️ Interview Pitfalls & Follow-ups
- Counting duplicate patterns within one user: a user must contribute at most one vote per pattern, hence the
set(combinations(...)). - Forgetting to sort by timestamp: the visit order would be arbitrary, and the pattern depends on chronology.
- Breaking ties the wrong way: the tie-break is the lexicographically smallest pattern, which
minover the tuples provides. - Using contiguous subarrays instead of combinations: the pattern is a subsequence of the user's visits, not necessarily consecutive.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
用户网站访问行为分析
给定三个数组 username、timestamp 和 website,三者长度相同,第 i 项表示用户 username[i] 在时刻 timestamp[i] 访问了网站 website[i] 。我们定义一个「访问模式」为某用户在 时间顺序 下访问的三个 不同 网站的序列。请你找出所有用户中出现次数最多的访问模式。如果有多个模式出现次数相同,返回 字典序最小 的那个。约束:3 ≤ username.length ≤ 50;1 ≤ timestamp[i] ≤ 10^9;timestamp 互不相同;1 ≤ website[i].length ≤ 10。
核心要点
- 三步走(标准解) :① 按 timestamp 排序,还原每位用户的真实访问顺序;② 对每位用户枚举所有长度为 3 的 组合 (保持时间顺序);③ 统计每个组合被多少个用户使用过,取最优。
- 为什么用「组合」而非「排列」 :三元组必须保持访问的时间顺序,因此枚举 i < j < k 的下标组合即可。
- 为什么同一用户内要去重 :同一个三元组可能被同一用户在多次不同访问中重复出现(如访问了 5 个网站),但统计的是「多少 用户 使用了该模式」,因此每个用户对每个模式只贡献 1。
- tie-break 技巧 :先按字典序排序,再用 max(key=次数) 。Python 的 max 返回 第一个 最大值元素,因此自然取到字典序最小者。
常见陷阱
- 忘记按 timestamp 排序 :输入数组不一定按时间有序,不排序会导致访问顺序错乱,三元组完全错误。
- 用排列而非组合 :必须保持时间顺序, i < j < k 的组合才是合法模式。
- 同一用户内未去重 :若某用户访问了 5 个网站,同一个三元组可能出现多次,会把它错误地计为多次使用。必须用 set 去重。
- tie-break 写错 :需要「次数最多」且「字典序最小」。写成 max(patterns, key=lambda p: (patterns[p], p)) 会得到字典序 最大 的,必须用 sorted + max(key=次数) 的组合。
参考实现
from collections import Counter, defaultdict
class Solution:
def mostVisitedPattern(self, username: list[str], timestamp: list[int],
website: list[str]) -> list[str]:
# ① 按时间排序,还原真实访问顺序
visits = sorted(zip(timestamp, username, website))
user_sites = defaultdict(list)
for _, u, w in visits:
user_sites[u].append(w)
# ② 每位用户枚举所有长度为 3 的时间有序组合(同一用户内去重)
patterns = Counter()
for sites in user_sites.values():
combos = set()
n = len(sites)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
combos.add((sites[i], sites[j], sites[k]))
for c in combos:
patterns[c] += 1
if not patterns:
return []
# ③ 先按字典序排序,再取出现次数最多者(max 返回第一个最大值 -> 字典序最小)
best = max(sorted(patterns.items()), key=lambda kv: kv[1])
return list(best[0])