Similar Problems

Similar Problems not available

Logger Rate Limiter | Leet Code - Leetcode Solution

Companies:

LeetCode:  Logger Rate Limiter | Leet Code Leetcode Solution

Difficulty: Unknown

Topics: hash-table  

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.

Complexity Analysis:

  • Time Complexity: O(1)

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

Logger Rate Limiter | Leet Code Solution Code

1