Python solution using OrderedDict, only store messages within 10 seconds

  • 0

    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:
                if message not in self.table:
                    self.table[message] = timestamp
                    return True
                    return False
        # Your Logger object will be instantiated and called as such:
        # obj = Logger()
        # param_1 = obj.shouldPrintMessage(timestamp,message)

  • 0

    Just like what you have figured out, you need to convert the view to list every time you can shouldPrint(), which is an O(n) operation. This is an unacceptable runtime.

Log in to reply

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