AlgoInsight

DSA problem

Logger Rate Limiter

EasyData Structure DesignPattern: Data Structure Designtop600GoogleAmazonMicrosoftAppleFacebook

Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most once every 10 seconds (i.e., a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10).

Implement the Logger class with two methods. Logger() initializes the logger object with no messages. shouldPrintMessage(timestamp, message) returns true if the message should be printed in the given timestamp, otherwise returns false.

The natural data structure is a hash map keyed by message string, with values storing the last timestamp at which that message was allowed through. On every call we look up the message: if it is missing, or if the stored timestamp is more than 10 seconds in the past, we accept it and overwrite the timestamp; otherwise we reject it.

This gives O(1) expected time per call and O(U) space where U is the number of unique messages ever seen. A subtle production concern is that the map grows unbounded over very long runs — a real system would either evict entries whose last-seen timestamp falls outside the cooldown window or back the storage with a TTL cache. The LeetCode version expects the simple unbounded map, which is what the canonical solution implements.

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: At t=1 "foo" and t=2 "bar" are first seen, so both print. "foo" at t=3 and "bar" at t=8 are still inside their 10-second cooldown. "foo" at t=10 is still blocked (10 - 1 < 10), but at t=11 it is finally allowed because 11 - 1 = 10.
Example 2
Input: ["Logger","shouldPrintMessage","shouldPrintMessage"] [[],[1,"hello"],[11,"hello"]]
Output: [null,true,true]
Explanation: The second "hello" at t=11 satisfies 11 - 1 >= 10, so it is allowed and the stored timestamp is updated to 11.
Example 3
Input: ["Logger","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage"] [[],[0,"a"],[1,"a"],[10,"a"]]
Output: [null,true,false,true]
Explanation: "a" prints at t=0, is blocked at t=1, and is allowed again at t=10 because 10 - 0 = 10.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

hash-tabledesigndata-stream

Browse all DSA problems