Rate-limited event logger
Build a logger that rate-limits repeated events in a stream. Each event has a string name and an integer timestamp in seconds. Timestamps arrive in non-decreasing order, and several events can share a timestamp.
An event prints only if no event with the same name was printed in the last window seconds. An event that is not printed does not restart the cooldown for its name.
Implement EventLogger:
-
EventLogger(window: int)creates a logger with a cooldown ofwindowseconds (window >= 0). -
should_print(timestamp: int, name: str) -> boolreturnsTrueif the event prints, and records it. Otherwise it returnsFalse.
A name printed at time p can print again at any time t with t - p >= window.
Constraints
- Up to 10^5 calls to
should_print. -
0 <= timestamp <= 10^9. Names are short ASCII strings. - Aim for O(1) amortized time per call. Be ready to talk about memory when the stream runs forever with many distinct names.
Example 1
logger = EventLogger(5)
logger.should_print(1, "play") -> True
logger.should_print(2, "pause") -> True
logger.should_print(4, "play") -> False # printed 3s ago
logger.should_print(6, "play") -> True # exactly 5s later
logger.should_print(6, "play") -> False # already printed at 6
Example 2
logger = EventLogger(5)
logger.should_print(6, "play") -> True
logger.should_print(9, "play") -> False # dropped; does not reset the cooldown
logger.should_print(11, "play") -> True # 5s after the print at 6
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.

