Logger Rate Limiter

Updated on 06 June, 2025
Logger Rate Limiter header image

Your document is well-written and follows the expected format closely. I’ve made a few minor refinements for consistency, formatting, and clarity—especially around the Examples section and code formatting.

Here's the production-ready version:


Problem Statement

A logging system receives messages along with their timestamps. Each unique message has a restriction: it can only be printed once every 10 seconds. That means if a message is printed at timestamp t, any identical message attempted before t + 10 should be rejected.

Implement the Logger class with the following methods:

  • Logger(): Initializes the logging system.
  • bool shouldPrintMessage(int timestamp, string message): Returns true if the message should be printed at the given timestamp; otherwise, returns false.

Timestamps are given in non-decreasing order.

Examples

Example 1

Input:

["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]

Output:

[null, true, true, false, false, false, true]

Explanation:

Logger logger = new Logger();
logger.shouldPrintMessage(1, "foo");  // true: first occurrence, next allowed at 11
logger.shouldPrintMessage(2, "bar");  // true: first occurrence, next allowed at 12
logger.shouldPrintMessage(3, "foo");  // false: 3 < 11
logger.shouldPrintMessage(8, "bar");  // false: 8 < 12
logger.shouldPrintMessage(10, "foo"); // false: 10 < 11
logger.shouldPrintMessage(11, "foo"); // true: 11 >= 11, next allowed at 21

Constraints

  • 0 <= timestamp <= 10⁹
  • Each timestamp is non-decreasing.
  • 1 <= message.length <= 30
  • At most 10⁴ calls will be made to shouldPrintMessage.

Approach and Intuition

To manage log requests efficiently:

  1. Use a Hash Map: Store each message along with the next valid timestamp when it can be printed again.

  2. Constructor Initialization: When the Logger object is initialized, create an empty hash map.

  3. Handle Logging:

    • For shouldPrintMessage(timestamp, message):

      • If the message does not exist in the map or timestamp >= map[message], update map[message] = timestamp + 10 and return true.
      • Otherwise, return false.

This approach ensures each call operates in constant time, O(1), and efficiently supports up to 10⁴ calls.

Solutions

  • Java
java
class LogPrinter {
  private HashMap<String, Integer> messageTimestampMap;

  public LogPrinter() {
    messageTimestampMap = new HashMap<String, Integer>();
  }

  public boolean canPrint(int timestamp, String message) {

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

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

The code provided in Java implements a rate limiter for a logging system. This system ensures that the same message is not printed more than once within a 10-second interval. The main components of the solution are:

  • A class named LogPrinter which contains the core functionality of the logger.
  • A private HashMap named messageTimestampMap, used to store messages and their respective last printed timestamps.

Features of the LogPrinter class include:

  • A constructor that initializes the messageTimestampMap.
  • A method named canPrint that:
    • Takes a timestamp and a message as parameters.
    • Checks if the message is present in the messageTimestampMap.
      • If not present, logs the message with the current timestamp and allows the message to be printed.
      • If present, it compares the current timestamp with the last printed timestamp.
        • If the difference is 10 seconds or more, updates the timestamp and allows the message to be printed.
        • Otherwise, prevents the message from being printed.

This implementation is effective for managing and limiting the rate at which messages are logged based on their timestamps and content. It ensures each message is printed at most once every 10 seconds, thereby preventing spam or repeated logging of the same message within a short period.

Comments

No comments yet.