Logger Rate Limiter Problem
Description
LeetCode Problem 359.
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 theloggerobject.bool shouldPrintMessage(int timestamp, string message)Returnstrueif themessageshould be printed in the giventimestamp, otherwise returnsfalse.
Example 1:
Input
["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
Output
[null, true, true, false, false, false, true]
Explanation
Logger logger = new Logger();
logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11
logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12
logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false
logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false
logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false
logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is 11 + 10 = 21
Constraints:
0 <= timestamp <= 10^9- Every
timestampwill be passed in non-decreasing order (chronological order). 1 <= message.length <= 30- At most
10^4calls will be made toshouldPrintMessage.
Solution
Approach: Hash Map of the Next Allowed Time
For each message, all we need to know is the earliest time it may be printed again. Keep a hash map from message to that timestamp.
When shouldPrintMessage(timestamp, message) is called:
- If the message is in the map and
timestampis still smaller than its stored time, returnfalse. Don't change the map: only a message that actually prints starts a new 10-second window. - Otherwise print it: store
timestamp + 10for the message and returntrue.
The boundary is inclusive. A message printed at t may print again at exactly t + 10, which is why we compare with < (the example prints "foo" at 1 and again at 11). Several calls may share a timestamp. Since the times never decrease, the stored value is always correct.
Complexity: O(1) time per call on average (O(L) to hash a message of length L). O(M) space for M distinct messages.
class Logger:
def __init__(self):
self.next_allowed = {} # message -> first timestamp at which it may be printed again
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
if timestamp < self.next_allowed.get(message, 0):
return False
self.next_allowed[message] = timestamp + 10
return True