Design a logger system that receives a stream of messages along with their timestamps.…
- User
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
twill prevent other identical messages from being printed until timestampt + 10).All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the
Loggerclass: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 <= 109- Every
timestampwill be passed in non-decreasing order (chronological order). 1 <= message.length <= 30- At most
104calls will be made toshouldPrintMessage.
- Assistantpython
class Logger: def __init__(self): self.message_timestamps = {} def shouldPrintMessage(self, timestamp: int, message: str) -> bool: if message not in self.message_timestamps or timestamp - self.message_timestamps[message] >= 10: self.message_timestamps[message] = timestamp return True return Falseexplanation The algorithm initializes an empty map to store message timestamps. The
shouldPrintMessagefunction takes input parameterstimestampandmessage. It checks if the message is in the map or not. If the message is not in the map or the difference between the given timestamp and the message's timestamp is greater than or equal to 10, it updates the message's timestamp in the map with the given timestamp, and the function returnstrue. If the difference is less than 10, the function returnsfalse. This ensures that messages will only be printed at most every 10 seconds.