Similar Problems

Similar Problems not available

Logger Rate Limiter - Leetcode Solution

Companies:

LeetCode:  Logger Rate Limiter Leetcode Solution

Difficulty: Easy

Topics: design hash-table  

Logger Rate Limiter is a problem on LeetCode that asks you to implement a logger that can output messages, but limit the rate messages are output. Specifically, the logger should only output a message if it hasn't been seen in the last 10 seconds.

To solve the Logger Rate Limiter problem, we can use a hash table to store the last timestamp that a given message was seen. We can then compare the current timestamp to the last seen timestamp for a message to determine whether or not that message should be logged.

Here's an example solution in Python:

class Logger:
    def __init__(self):
        self.timestamp = {}
    
    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        if message in self.timestamp:
            if timestamp - self.timestamp[message] < 10:
                return False
        self.timestamp[message] = timestamp
        return True

In this solution, we create a hash table called timestamp to store the last seen timestamp for each message. In the shouldPrintMessage method, we check if the message has been seen before by checking if it's in the timestamp hash table. If it is, we compare the current timestamp to the last seen timestamp for that message. If the difference is less than 10 seconds, we return False because we don't want to print the message. Otherwise, we update the timestamp hash table with the current timestamp and return True, allowing the message to be printed.

Overall, this solution has a time complexity of O(n), where n is the number of messages seen by the logger, and a space complexity of O(m), where m is the number of unique messages seen by the logger. It's a simple and efficient solution that satisfies the requirements of the Logger Rate Limiter problem.

Logger Rate Limiter Solution Code

1