← Questions
Logger that reports its top K messages
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests heaps, hash maps and data structure design.
Build an in-memory logger. It receives messages with timestamps and, at any point, returns the k most frequent messages: over everything logged so far, and then over a given time interval.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
log(timestamp: int, message: str) -> None— timestamps arrive in non-decreasing order. -
top_k(k: int) -> list[str]— thekmost frequent messages so far, most frequent first; ties go to the alphabetically smaller message. - Part 2:
top_k_between(k: int, start: int, end: int) -> list[str]— the same, counting only messages withstart <= timestamp <= end.
Example
log(1, "disk full")
log(2, "timeout")
log(3, "disk full")
log(5, "auth failed")
log(6, "timeout")
log(7, "timeout")
top_k(2) -> ["timeout", "disk full"] # 3 and 2
top_k_between(2, 3, 6) -> ["auth failed", "disk full"] # all three appear once; alphabetical
top_k_between(1, 1, 3) -> ["disk full"]
Constraints
- Up to 10^6
logcalls; the number of distinct messages can be large. -
kis small compared with the number of distinct messages.
Clarifying questions
- How are ties broken?
- How often is
top_kcalled compared withlog? - Is the interval in Part 2 arbitrary, or always "the last N seconds"?
- Must answers be exact, or is an approximation acceptable at scale?
What a strong answer covers
- Part 1: a hash map of counts; for each query a heap of size
kover distinct messages, O(d log k); or an ordered structure keyed by(count, message)updated on eachlogfor O(log d) per log and O(k) per query. State which side you optimize. - Part 2: messages stored in time order; binary search for the interval's bounds, count inside it, then a heap of size
k. O(m + d log k) formmessages in the interval. - For a sliding "last N seconds" window: a queue of events and counts that are decremented as events expire.
- Tests: ties, empty intervals,
klarger than the number of messages.
Follow-ups
- Many interval queries over a long history: precompute counts per time bucket and merge the buckets.
- Too many distinct messages for memory: Count-Min sketch with a heap of heavy hitters.
- Messages that differ only in ids or numbers should count as one (template extraction).
Where it's asked
- Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
