Keeping only recent messages

  • 0

    To avoid using any more space than needed: when a new message arrives, delete all stored messages older than 10 seconds.
    This way we only keep the messages received in the last 10 seconds, which are the ones we care about.

    Higher time complexity than the other Python solution (we visit all stored messages), but less spatial complexity.
    Better if the amount of possible messages is high, but the frequency is low.

    class Logger(object):
        def __init__(self):
            self.ok = {}
        def shouldPrintMessage(self, timestamp, message):
            for msg, ts in self.ok.items():
                if timestamp >= (ts + 10):
                    del self.ok[msg]
            if message in self.ok:
                return False
            self.ok[message] = timestamp
            return True

Log in to reply

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