Logger Rate Limiter
Problem
Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t
will prevent other identical messages from being printed until timestamp t + 10
).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger
class:
Logger()
Initializes thelogger
object.bool shouldPrintMessage(int timestamp, string message)
Returnstrue
if themessage
should be printed in the giventimestamp
, otherwise returnsfalse
.
Constraints
0 <= timestamp <= 109
- Every
timestamp
will be passed in non-decreasing order (chronological order). 1 <= message.length <= 30
- At most
104
calls will be made toshouldPrintMessage
.
Solution
The problem Logger Rate Limiter
can be solved using a hash map to store the latest timestamp
of message
s that were successfully printed.
Implementation
class Logger
{
private:
unordered_map<string, int> cache;
public:
Logger() {}
bool shouldPrintMessage(int timestamp, string message)
{
if (cache[message] <= timestamp)
{
cache[message] = timestamp + 10;
return true;
}
return false;
}
};
/**
* Your Logger object will be instantiated and called as such:
* Logger* obj = new Logger();
* bool param_1 = obj->shouldPrintMessage(timestamp,message);
*/