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 the logger object.
bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp, otherwise returns false.
classLogger{private:unordered_map<string,int>msgToTime;public:Logger(){}boolshouldPrintMessage(inttimestamp,stringmessage){if(!msgToTime.count(message)){msgToTime[message]=timestamp;returntrue;}if(timestamp-msgToTime[message]>=10){msgToTime[message]=timestamp;returntrue;}else{returnfalse;}}};/** * Your Logger object will be instantiated and called as such: * Logger* obj = new Logger(); * bool param_1 = obj->shouldPrintMessage(timestamp,message); */
Time complexity: ;
Space complexity: , where is is the size of all incoming messages. Over the time, the hash table would have an entry for each unique message that has appeared.
Another way (reduce space complexity, but add time complexity):