Python solution using OrderedDict, only store messages within 10 seconds


  • 0
    S

    This solution only needs to store messages within 10 seconds.
    self.table.items()[0] would get the first item inserted (in last 10 seconds). By comparing the first message and the incoming message timestamp, we can remove the messages that was beyong the 10 seconds window since we don't need to consider them anymore.

    in python 3, items() would return an iterable dict view object, so I converted it to list using list().

       class Logger(object):
        
            def __init__(self):
                self.table = collections.OrderedDict([])
        
            def shouldPrintMessage(self, timestamp, message):
                while self.table and list(self.table.items())[0][1] + 10 <= timestamp:
                    self.table.popitem(last=False)
                if message not in self.table:
                    self.table[message] = timestamp
                    return True
                else:
                    return False
                
        
        
        # Your Logger object will be instantiated and called as such:
        # obj = Logger()
        # param_1 = obj.shouldPrintMessage(timestamp,message)

Log in to reply
 

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