DSA problem
Logger Rate Limiter
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
["Logger","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage"]
[[],[1,"foo"],[2,"bar"],[3,"foo"],[8,"bar"],[10,"foo"],[11,"foo"]][null,true,true,false,false,false,true]["Logger","shouldPrintMessage","shouldPrintMessage"]
[[],[1,"hello"],[11,"hello"]][null,true,true]["Logger","shouldPrintMessage","shouldPrintMessage","shouldPrintMessage"]
[[],[0,"a"],[1,"a"],[10,"a"]][null,true,false,true]Constraints
- 0 <= timestamp <= 10^9
- Every timestamp will be passed in non-decreasing order (chronological).
- 1 <= message.length <= 30
- At most 10^4 calls will be made to shouldPrintMessage.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.