Logger Rate Limiter solution and explanation
9 more videos on this problem
LOGGER RATE LIMITER | LEETCODE # 359 | PYTHON SOLUTIONCracking FAANG · 7:33 · 11K views
Logger Rate Limiter | LeetCode 359 System DesignDestination FAANG · 14:30 · 3K views
LoggerRateLimiter - Solution to LeetCode problem 359 - Logger Rate LimiterLEETCODE MASTER · 5:32 · 3K views
Google Interview Question - Logger Rate Limiter - LeetCode 359AlgoJS · 3:43 · 1K views
Microsoft Coding Interview Question | Leetcode 359 | Logger Rate LimiterWorkWithGoogler · 6:12 · 1K views
Leetcode 359: Logger Rate Limiter C++ In Plain English (Google Interview)Algo Genius · 4:52 · 891 views
Leetcode 359- Logger Rate Limiter Java solution | Crack Coding Interview | FAANG interview questionSoftWiz Circle · 4:45 · 819 views
LeetCode 359. Logger Rate Limiter | JSer - JavaScript & AlgorithmJSer · 3:39 · 590 views
359. Logger Rate Limiter - Week 2/5 Leetcode May ChallengeProgramming Live with Larry · 3:40 · 502 views
leetcode 359 - Logger Rate LimiterlitCode · 11:07 · 315 views
The 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 theloggerobject.bool shouldPrintMessage(int timestamp, string message)Returnstrueif themessageshould be printed in the giventimestamp, otherwise returnsfalse.
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 Logger logger = new Logger(); logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11 logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12 logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is 11 + 10 = 21
Constraints:
0 <= timestamp <= 109- Every
timestampwill be passed in non-decreasing order (chronological order). 1 <= message.length <= 30- At most
104calls will be made toshouldPrintMessage.
Approach overview
Problem Overview: You need to design a logger system that decides whether a message should be printed at a given timestamp. Each message can only be printed once every 10 seconds. If the same message appears again within that window, the logger must suppress it.
Approach 1: Brute Force Log Scan (O(n) time, O(n) space)
Store every printed message with its timestamp in a list or queue. When a new request arrives, iterate through the stored logs to find the most recent occurrence of that message. If the difference between the current timestamp and the stored timestamp is at least 10 seconds, allow printing; otherwise reject it. This approach works but becomes inefficient as the log grows because every query may require scanning multiple entries. The time complexity per request can degrade to O(n), while space complexity is also O(n) for storing past messages.
Approach 2: Hash Table with Last Printed Timestamp (O(1) time, O(n) space)
Use a hash table that maps each message string to the last timestamp when it was printed. For every incoming message, perform a constant-time lookup in the map. If the message is not present, or if currentTimestamp - lastTimestamp >= 10, update the stored timestamp and return true. Otherwise return false. Hash lookups and updates run in O(1) average time, making this approach extremely efficient for continuous streams of log events.
This technique fits naturally with design problems where the system must respond quickly to frequent queries. Since messages arrive in chronological order (a typical assumption in data stream problems), the stored timestamps remain valid without extra cleanup logic. The space usage grows with the number of unique messages and is O(n).
Recommended for interviews: The hash table approach is the expected solution. It demonstrates the ability to convert repeated lookups into constant-time operations using a map. Mentioning the brute force scan shows you understand the baseline, but implementing the hash map version shows strong problem-solving and system design instincts.
Solution
We use a hash table ts to store the next available print timestamp for each message. When the shouldPrintMessage method is called, we check whether the current timestamp is greater than or equal to the next available print timestamp for the message. If so, we update the next available print timestamp to the current timestamp plus 10 and return true; otherwise, we return false.
The time complexity is O(1). The space complexity is O(m), where m is the number of distinct messages.
class Logger:
def __init__(self):
self.ts = {}
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
t = self.ts.get(message, 0)
if t > timestamp:
return False
self.ts[message] = timestamp + 10
return True
# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)class Logger {
private Map<String, Integer> ts = new HashMap<>();
public Logger() {
}
public boolean shouldPrintMessage(int timestamp, String message) {
int t = ts.getOrDefault(message, 0);
if (timestamp < t) {
return false;
}
ts.put(message, timestamp + 10);
return true;
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/class Logger {
public:
Logger() {
}
bool shouldPrintMessage(int timestamp, string message) {
if (ts.contains(message) && ts[message] > timestamp) {
return false;
}
ts[message] = timestamp + 10;
return true;
}
private:
unordered_map<string, int> ts;
};
/**
* Your Logger object will be instantiated and called as such:
* Logger* obj = new Logger();
* bool param_1 = obj->shouldPrintMessage(timestamp,message);
*//**
* Initialize your data structure here.
*/
var Logger = function () {
this.limiter = {};
};
/**
* Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity.
* @param {number} timestamp
* @param {string} message
* @return {boolean}
*/
Logger.prototype.shouldPrintMessage = function (timestamp, message) {
const t = this.limiter[message] || 0;
if (t > timestamp) {
return false;
}
this.limiter[message] = timestamp + 10;
return true;
};
/**
* Your Logger object will be instantiated and called as such:
* var obj = new Logger()
* var param_1 = obj.shouldPrintMessage(timestamp,message)
*/type Logger struct {
ts map[string]int
}
func Constructor() Logger {
return Logger{ts: make(map[string]int)}
}
func (this *Logger) ShouldPrintMessage(timestamp int, message string) bool {
if t, ok := this.ts[message]; ok && timestamp < t {
return false
}
this.ts[message] = timestamp + 10
return true
}
/**
* Your Logger object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.ShouldPrintMessage(timestamp,message);
*/Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Log Scan | O(n) per request | O(n) | Conceptual baseline or very small log sizes |
| Hash Table (Last Timestamp) | O(1) average | O(n) | Best choice for real-time logging systems and interview solutions |
Frequently asked questions
Is Logger Rate Limiter easy or hard?
Logger Rate Limiter is classified as an Easy problem on LeetCode. The core idea is straightforward once you recognize that storing the last timestamp in a hash map allows constant-time decisions for each message.
Logger Rate Limiter Python/Java solution
The standard implementation uses a dictionary in Python or a HashMap in Java to track the last printed timestamp for each message. Each call checks the stored timestamp and updates it if the message can be printed.
How to solve Logger Rate Limiter in O(1)?
Maintain a hash map where the key is the message and the value is the last printed timestamp. For each new request, look up the message and check if currentTimestamp minus storedTimestamp is at least 10. If true, update the timestamp and return true; otherwise return false.
What is the best approach for Logger Rate Limiter?
The most efficient approach uses a hash table that maps each message to the last timestamp when it was printed. When a new message arrives, check the stored timestamp and allow printing only if at least 10 seconds have passed. This gives O(1) average time per request and O(n) space for storing unique messages.
Is Logger Rate Limiter asked at Google/Amazon/Meta?
Logger Rate Limiter is a common design-style interview problem seen at companies like Google, Amazon, and Meta. It tests understanding of hash tables, efficient lookups, and basic system design concepts for handling streaming data.
What data structure is used in Logger Rate Limiter?
A hash table (hash map) is the primary data structure used. It stores each message string as a key and the last printed timestamp as the value, enabling constant-time checks and updates.
What is the time complexity of Logger Rate Limiter?
Using the optimal hash table design, each logger check runs in O(1) average time because message lookups and updates are constant-time hash operations. Space complexity is O(n), where n is the number of unique messages stored in the logger.
