Logger Rate Limiter - Problem
Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger class:
Logger()Initializes the logger object.bool shouldPrintMessage(int timestamp, string message)Returnstrueif the message should be printed in the given timestamp, otherwise returnsfalse.
Input & Output
Example 1 — Basic Logger Operations
$
Input:
operations = ["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"], parameters = [[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"]]
›
Output:
[null, true, true, false, false, true]
💡 Note:
Logger() initializes. shouldPrintMessage(1, "foo") returns true (first time). shouldPrintMessage(2, "bar") returns true (first time). shouldPrintMessage(3, "foo") returns false ("foo" was printed 2 seconds ago, less than 10). shouldPrintMessage(8, "bar") returns false ("bar" was printed 6 seconds ago). shouldPrintMessage(10, "foo") returns true ("foo" was printed 9 seconds ago, now exactly 10 seconds have passed).
Example 2 — Same Timestamp Messages
$
Input:
operations = ["Logger", "shouldPrintMessage", "shouldPrintMessage"], parameters = [[], [5, "hello"], [5, "hello"]]
›
Output:
[null, true, false]
💡 Note:
First "hello" at timestamp 5 is allowed. Second "hello" at same timestamp 5 is blocked because 5 - 5 = 0 < 10 seconds.
Example 3 — Exact 10 Second Boundary
$
Input:
operations = ["Logger", "shouldPrintMessage", "shouldPrintMessage"], parameters = [[], [0, "test"], [10, "test"]]
›
Output:
[null, true, true]
💡 Note:
"test" at timestamp 0 is allowed. "test" at timestamp 10 is allowed because 10 - 0 = 10 seconds (not less than 10).
Constraints
- 0 ≤ timestamp ≤ 109
- Every timestamp will be passed in non-decreasing order (chronological order)
- 1 ≤ message.length ≤ 30
- At most 104 calls will be made to shouldPrintMessage
Visualization
Tap to expand
Understanding the Visualization
1
Input Stream
Messages arrive with timestamps in chronological order
2
Rate Limiting
Block duplicate messages within 10 seconds
3
Output Decision
Return true/false for each shouldPrintMessage call
Key Takeaway
🎯 Key Insight: Only track the last timestamp per unique message using a hash map for O(1) rate limiting decisions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code