Logger Rate Limiter | Leet Code

Companies:
  • Google Interview Questions
  • Uber Interview Questions

Logger Rate Limiter | Leet Code

Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.

Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.

It is possible that several messages arrive roughly at the same time.

Example:

Logger logger = new Logger();

// logging string “hello” at timestamp 1

logger.shouldPrintMessage(1, “hello”); returns true;

// logging string “hy” at timestamp 2

logger.shouldPrintMessage(2,“hy”); returns true;

// logging string “hello” at timestamp 3

logger.shouldPrintMessage(3,“hello”); returns false;

// logging string “hy” at timestamp 8

logger.shouldPrintMessage(8,“hy”); returns false;

// logging string “hello” at timestamp 10

logger.shouldPrintMessage(10,“hello”); returns false;

// logging string “hello” at timestamp 11

logger.shouldPrintMessage(11,“hello”); returns true;

Solution:

  • We will use hash table to solve this problem. The message can be stored as a key and the timestamp is stored as a value in hash table.

  • This will keep the record of the time and message in a hash table.

  • We will print the message only if:

    • We have not seen the message before, or,
    • The message was printed was printed more than 10 sec ago.
  • In both the cases we will update the hash table with the timestamp which is the latest one with the message.

Implementation:

Java:

class Logger {
  private HashMap<String, Integer> msgDict;

  /** Initialize your data structure here. */
  public Logger() {
    msgDict = new HashMap<String, Integer>();
  }

  /**
   * Returns true if the message should be printed in the given timestamp, otherwise returns false.
   */
  public boolean shouldPrintMessage(int timestamp, String message) {

    if (!this.msgDict.containsKey(message)) {
      this.msgDict.put(message, timestamp);
      return true;
    }

    Integer oldTimestamp = this.msgDict.get(message);
    if (timestamp - oldTimestamp >= 10) {
      this.msgDict.put(message, timestamp);
      return true;
    } else
      return false;
  }
}

Complexity Analysis:

  • Time Complexity: O(1)

  • Space Complexity: O(M), where M is the size of the incoming message.

Scroll to Top