π Problem Statement
Design a logger system that receives a stream of messages along with timestamps. Each message should only be printed if it was not printed in the last 10 seconds.
Implement the Logger
class:
python
Logger():
Initializes the logger object.
bool shouldPrintMessage(int timestamp, string message):
Returns true if the message should be printed at the given timestamp,
otherwise returns false.
Constraints:
- All timestamps are in seconds and strictly increasing.
- The
timestamp
is a positive integer up to 2^31 - 1
.
π§ Key Idea
We only need to remember the last printed timestamp of each message.
The ideal data structure is a hashmap that maps:
python
message β last printed timestamp
Check if:
python
current_timestamp - last_timestamp >= 10
π Python Code
python
class Logger:
def __init__(self):
self.msg_map = {}
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
if message not in self.msg_map or timestamp - self.msg_map[message] >= 10:
self.msg_map[message] = timestamp
return True
else:
return False
π Step-by-Step Explanation
1. Initialize
python
self.msg_map = {}
- Stores the last printed time for each unique message.
2. Check If Message Can Be Printed
python
if message not in self.msg_map or timestamp - self.msg_map[message] >= 10
- If itβs a new message or the last time it was printed was β₯10 seconds ago, allow it.
3. Update Timestamp
python
self.msg_map[message] = timestamp
- Record the latest time this message was printed.
4. Else Return False
π‘ Example Trace
python
logger = Logger()
logger.shouldPrintMessage(1, "foo") # True
logger.shouldPrintMessage(2, "bar") # True
logger.shouldPrintMessage(3, "foo") # False
logger.shouldPrintMessage(10, "foo") # False
logger.shouldPrintMessage(11, "foo") # True
β±οΈ Time & Space Complexity
OperationComplexityTimeO(1)SpaceO(n)
π§΅ Final Thoughts
This is a perfect warm-up problem for:
- Designing efficient key-value data structures
- Implementing rate limiting logic
- Practicing O(1) time complexity checks