← 返回 snowflake 的题目列表Top-K trending search terms with per-user de-duplication
类型:online_judge
Design and implement a function/class to return the top k trending search terms from a stream of search events.
Rules:
Each event contains: user_id and term.
Multiple searches of the same term by the same user count only once (deduplicate by (user_id, term) before counting).
Popularity is defined as the number of distinct users who searched the term (or equivalently the deduplicated count).
Requirements:
Implement APIs:
record(user_id: str, term: str) -> None: record a search event.
top_k(k: int) -> List[str]: return the current top k terms.
Explain your data structures and analyze time/space complexity for both APIs.
Handle edge cases:
What to return if k exceeds the number of distinct terms.
Tie-breaking when multiple terms share the same popularity (e.g., lexicographic order or arbitrary; must be specified).
Scale:
Total number of events N can be large; consider efficiency.
Example:
Events: (u1, "apple"), (u1, "apple"), (u2, "apple"), (u2, "banana")
After dedup: apple=2, banana=1
top_k(1) returns ["apple"].
Example
Input
record u1 apple
record u1 apple
record u2 apple
top_k 1
Output
apple