Python solution with detailed explanation


  • 0
    G

    Solution

    Logger Rate Limiter https://leetcode.com/problems/logger-rate-limiter/

    • Design a cache with key as message digest and value as (message, timestep)
    • Get the hash for the message.
    • If the hash is not in cache, then add it with timestamp and return True.
    • If the hash is in cache and if t - cache[hash,1] >= 10, then update timestamp for this message to be t and return True.
    • If the hash is in cache and t - cache[hash,1] < 10, just return False. Do not update the timestamp - Why? Because as per condition in the problem, we only update the time stamp when we print the message.
    import hashlib
    
    class Logger(object):
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.cache = {}
            return
        
        def hash_str(self, m):
            return hashlib.md5(m.encode()).hexdigest()
    
        def shouldPrintMessage(self, t, m):
            """
            Returns true if the message should be printed in the given timestamp, otherwise returns false.
            If this method returns false, the message will not be printed.
            The timestamp is in seconds granularity.
            :type timestamp: int
            :type message: str
            :rtype: bool
            """
            h = self.hash_str(m)
            cache = self.cache
            if h not in cache:
                cache[h] = [m, t]
                return True
            elif h in cache and t-cache[h][1] >= 10:
                cache[h][1] = t
                return True
            elif h in cache and t-cache[h][1] < 10:
                return False
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.