📝 Problem Details
- Title:
359. Logger Rate Limiter - Link: https://leetcode.com/problems/logger-rate-limiter/
- Difficulty: Easy
- Tags/Categories: Hashing Design
design a logger that receives a stream of messages and their timestamps each unique message should only be printed at most every 10 seconds (a message printed at time
twill prevent other identical messages from being printed untilt+10) all messages will come in chronological order, several messages may arrive at the same timestamp
implement the
Logger classLogger()initializes theloggerobjectbool shouldPrintMessage(int timestamp, string message)- returns true if the message should be printed in the given timestamp, otherwise returns false
💡 Explanation of Solution
Hashmap for Storing Message Timestamps
- maintain a hashmap (unordered_map<string,int>) where:
- key = message string
- value = earliest timestamp when this message was last seen
- when a new message arrives:
- if the message is not in the hashmap, insert it with the current timestamp and return true
- if the message is in the hashmap:
- check if the current timestamp >= stored_timestamp + 10, update the timestamp and return true
- otherwise, return false
⌛ Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(n)
💻 Implementation of Solution
class Logger {
private:
unordered_map<string, int> messageTimestamp;
public:
Logger() {}
bool shouldPrintMessage(int timestamp, string message) {
if (messageTimestamp.find(message) == messageTimestamp.end() ||
timestamp >= messageTimestamp[message] + 10) {
messageTimestamp[message] = timestamp;
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);
*/