Logger Rate Limiter

Here’s a way to implement the Logger class as described in the problem statement:

  1. Initialize a Dictionary: Keep a dictionary to store the messages along with the next allowed timestamp for each message.
  2. Check and Update the Timestamp: For each incoming message, check if it’s allowed based on the current timestamp, and update the timestamp accordingly.

Below is the code implementing these steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Logger:
    def __init__(self):
        self.message_time = {} # Dictionary to store message and next allowed timestamp

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        # If the message is not in the dictionary, or the timestamp is greater or equal to the allowed time
        if message not in self.message_time or timestamp >= self.message_time[message]:
            self.message_time[message] = timestamp + 10 # Update the next allowed timestamp for this message
            return True
        else:
            return False

Explanation:

  • The message_time dictionary keeps track of each unique message and the next allowed timestamp for printing that message.
  • If the message is new or its next allowed timestamp is less than or equal to the current timestamp, the method returns true, and the next allowed timestamp is updated.
  • If the current timestamp is less than the next allowed timestamp for that message, the method returns false.

The time complexity of this approach is (O(1)) for both insertion and lookup. The space complexity depends on the number of unique messages, so in the worst case, it’s (O(N)), where (N) is the number of unique messages.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Logger:
    def __init__(self):
        self.history = {}  # stores past messages in the form {message: last print timestamp}

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        if message in self.history and timestamp - self.history[message] < 10:  # O(1)
            return False
        else:
            self.history[message] = timestamp  # O(1)
            return True