← Questions

Rate-limited event logger that drops repeats within a window

0
NetflixGoogleAmazonCodingLast asked Sep 2026

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 of window seconds (window >= 0).
  • should_print(timestamp: int, name: str) -> bool returns True if the event prints, and records it. Otherwise it returns False.

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

Clarifying questions

  • With window = 0, does every event print, including repeats at the same timestamp?
  • Is the cooldown per name only, with no global limit across names?
  • Will the stream run forever with an unbounded number of distinct names?
  • Is should_print called from one thread only?

What a strong answer covers

  • Keeps a dict from name to the time it last printed; prints when the name is absent or t - last >= window, then updates the time. O(1) per call.
  • Updates the time only on a print, so a dropped event never extends the cooldown (Example 2).
  • Gets the boundary right: exactly window seconds later prints (6 after 1 with window 5).
  • Bounds memory for an endless stream by evicting names whose last print is at least window old, using a queue of (time, name) in print order, which stays amortised O(1) because timestamps are non-decreasing.
  • Tests same-timestamp repeats, the exact boundary, dropped events, window = 0, and many distinct names.

Follow-ups

  • Make it safe under concurrent callers.
  • Allow a burst of n prints per window instead of one.
  • Handle events that arrive slightly out of order.
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