KatInterview

359. Logger Rate Limiter

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to design a logger system that filters incoming messages based on a time-based rate limit. Specifically, each unique message string should not be printed more than once every 10 seconds. We are given a stream of messages with timestamps, and we need to determine for each message whether it should be printed. The timestamps are guaranteed to be in non-decreasing chronological order.

Solution

Logger Rate Limiter in Python

class Logger:

    def __init__(self):
        # Dictionary to store the next allowed timestamp for each message.
        # Key: message string, Value: next allowed timestamp.
        self.next_timestamp_map = {}

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        # Check if the message is not in our dictionary (first time seeing it).
        if message not in self.next_timestamp_map:
            # It's a new message, so we should print it.
            # Record the next time this message is allowed to be printed.
            self.next_timestamp_map[message] = timestamp + 10
            return True
        
        # The message has been seen before. Check if enough time has passed.
        next_allowed_time = self.next_timestamp_map[message]
        if timestamp >= next_allowed_time:
            # Enough time has passed. We can print the message.
            # Update the next allowed time for this message.
            self.next_timestamp_map[message] = timestamp + 10
            return True
        else:
            # It's too soon to print the message again.
            return False


# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)

Logger Rate Limiter in Java

class Logger {
    // Map to store the next allowed timestamp for each message.
    // Key: message string, Value: next allowed timestamp.
    private Map<String, Integer> nextTimestampMap;

    public Logger() {
        nextTimestampMap = new HashMap<>();
    }
    
    public boolean shouldPrintMessage(int timestamp, String message) {
        // Check if the message is not in our map (first time seeing it) or
        // if the current timestamp is greater than or equal to the allowed timestamp.
        if (!nextTimestampMap.containsKey(message) || timestamp >= nextTimestampMap.get(message)) {
            // If either condition is true, we can print the message.
            // Update the map with the next allowed timestamp for this message.
            nextTimestampMap.put(message, timestamp + 10);
            return true;
        } else {
            // It's too soon to print the message again.
            return false;
        }
    }
}

/**
 * Your Logger object will be instantiated and called as such:
 * Logger obj = new Logger();
 * boolean param_1 = obj.shouldPrintMessage(timestamp,message);
 */

Logger Rate Limiter in C++

class Logger {
private:
    // Map to store the next allowed timestamp for each message.
    // Key: message string, Value: next allowed timestamp.
    unordered_map<string, int> next_timestamp_map;

public:
    Logger() {
        // The unordered_map is automatically initialized.
    }
    
    bool shouldPrintMessage(int timestamp, string message) {
        // Check if the message is not in our map (first time seeing it).
        if (next_timestamp_map.find(message) == next_timestamp_map.end()) {
            // It's a new message, so we should print it.
            // Record the next time this message is allowed to be printed.
            next_timestamp_map[message] = timestamp + 10;
            return true;
        }
        
        // The message has been seen before. Check if enough time has passed.
        int next_allowed_time = next_timestamp_map[message];
        if (timestamp >= next_allowed_time) {
            // Enough time has passed. We can print the message.
            // Update the next allowed time for this message.
            next_timestamp_map[message] = timestamp + 10;
            return true;
        } else {
            // It's too soon to print the message again.
            return false;
        }
    }
};

/**
 * Your Logger object will be instantiated and called as such:
 * Logger* obj = new Logger();
 * bool param_1 = obj->shouldPrintMessage(timestamp,message);
 */

Logger Rate Limiter in TypeScript

class Logger {
    // Map to store the next allowed timestamp for each message.
    // Key: message string, Value: next allowed timestamp.
    private nextTimestampMap: Map<string, number>;

    constructor() {
        this.nextTimestampMap = new Map<string, number>();
    }

    shouldPrintMessage(timestamp: number, message: string): boolean {
        // Check if the message is not in our map (first time seeing it).
        if (!this.nextTimestampMap.has(message)) {
            // It's a new message, so we should print it.
            // Record the next time this message is allowed to be printed.
            this.nextTimestampMap.set(message, timestamp + 10);
            return true;
        }

        // The message has been seen before. Check if enough time has passed.
        const nextAllowedTime = this.nextTimestampMap.get(message)!; // '!' asserts that the value is not undefined.
        if (timestamp >= nextAllowedTime) {
            // Enough time has passed. We can print the message.
            // Update the next allowed time for this message.
            this.nextTimestampMap.set(message, timestamp + 10);
            return true;
        } else {
            // It's too soon to print the message again.
            return false;
        }
    }
}

/**
 * Your Logger object will be instantiated and called as such:
 * var obj = new Logger()
 * var param_1 = obj.shouldPrintMessage(timestamp,message)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.