Skip to main content

Logger Rate Limiter

Leetcode #359, "Easy": Logger Rate Limiter

# https://leetcode.com/problems/logger-rate-limiter/
class Logger:

def __init__(self):
self.message_dict = {}

def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
# if message not in dict, register it. return true
if message not in self.message_dict:
self.message_dict[message] = timestamp

return True

# if current item timestamp minus the timestamp for the same item in the dict is greater than or equal to 10, then the message exists in the dict, but it has been greater than 10 seconds.
# so, overwrite its previous entry. return true.
if timestamp - self.message_dict[message] >= 10:
self.message_dict[message] = timestamp

return True

# otherwise, it's in the dictionary AND it has re-appeared within less than 10 seconds. So, return false
else:
return False

# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)