Top K Trending Topics Over a Sliding Time Window
Last updated: November 29, 2026
Quick Overview
Implement a tracker with `record(timestamp, topic)` and `top_k(now, k)` that returns the k topics mentioned most in the last W seconds, ties broken alphabetically. Timestamps are non-decreasing.
Meta
November 29, 20260
0
0 solved
Implement a tracker with `record(timestamp, topic)` and `top_k(now, k)` that returns the k topics mentioned most in the last W seconds, ties broken alphabetically. Timestamps are non-decreasing.
A Meta onsite question inspired by trending topics on Threads and Facebook. Beyond the code, interviewers probe how eviction interacts with counts and how you would trade exactness for memory at scale.
What the Interviewer Expects
- Keep a FIFO of events for window eviction
- Maintain per-topic counts updated on add and evict
- Select top k with a bounded heap rather than a full sort
- Define the window boundary precisely
- Discuss approximate structures for scale
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you handle out-of-order timestamps?
- Memory is too large for exact counts: what approximate method would you use?
- Make top_k O(k) per query at the cost of slower updates.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
record(ts, topic): one mention at time ts.top_k(now, k): topics with highest counts over(now - W, now], ties alphabetical.- Timestamps passed to both calls are non-decreasing.
- Return fe...
High-Level Design
State:
events: deque of(ts, topic)in arrival order.counts: topic to count within the window.
On every call, evict from the deque front while ts <= now - W, decrementing counts and ...