15% off all plans & roadmaps Use code
See plansLogger Rate Limiter
- LeetCode 359
- Easy
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: For each call, decide whether the same message printed within the last 10 seconds. Store each message's last printed timestamp in a hash map and compare against it in constant time.
Problem
You are building a logger that receives a stream of messages. Each message arrives with a timestamp in seconds. Implement the Logger class:
Logger()creates the logger object.bool shouldPrintMessage(int timestamp, string message)returnstrueif the message should be printed at the given timestamp, andfalseotherwise.
A message should print only if the same message has not printed in the last 10 seconds. The check includes the current timestamp. Each call has a timestamp that is at least as large as the timestamp of the call before it.
Example 1
Input: operations = ["Logger", "shouldPrintMessage"], arguments = [[], [100, "unique"]] Output: [null, true]
Constraints
0 <= timestamp <= 10^91 <= message.length <= 30- At most
10^4calls will be made toshouldPrintMessage.
Return true if the message should be printed at the given timestamp, otherwise return false.
Constraints that matter
- Up to 10^4 calls rules out a scan of every past call on every new call, which would be about 10^8 steps in the worst case and too slow for a service.
- Timestamps up to 10^9 mean you must compare differences, not store a window of seconds. A map from message to time is far smaller than a per-second table.
- Timestamps never decrease. That means an older print can never block a call that a newer print would allow, so only the latest print of each message matters.
- Messages are at most 30 characters. Hashing a message is constant work, so each map operation is cheap.
Hints
Hint 1
This is a design problem.
Hint 2
Keep a list of every printed call, as a pair of timestamp and message.
Solution
Intuition
This is a design problem. You must keep state across calls on one object, and that state must answer a lookup question quickly. The rule depends only on when each message last printed. A message printed at time t stays blocked until time t + 10.
Picture a doorman's clipboard with one line per guest, where the time each guest last walked in is written. The clipboard is the hash map, each guest's written time is the stored timestamp, and a turned-away guest changes nothing.
Notice what the rule ignores. Other messages do not change a message's decision. Rejected calls change nothing either. So you need one number per message, its last printed timestamp. That points to a hash map keyed by the message string, the standard tool for per-key state.
Timestamps never decrease, so the most recent print is the only one that can still block a call. Older prints already sit outside the window. One value per message is enough.
Worked example
Input: operations = ["Logger", "shouldPrintMessage"], arguments = [[], [100, "unique"]] Output: [null, true] Explanation: The constructor returns nothing, so the first entry is null. The one printing call is at timestamp 100 for the message unique. Nothing was printed before, so nothing can block it, and the method returns true.
Approach 1: Brute force scan of printed history
Keep a list of every printed call, as a pair of timestamp and message. For each new call, scan the whole list for the same message and check whether any entry is less than 10 seconds old. This is correct, because it checks every print that could block the call.
It is slow because the list keeps growing. Each call reads entries for other messages and for prints that expired long ago. Those reads cannot change the answer, but the scan still pays for them.
Steps
- In the constructor, create two empty lists: one for printed timestamps and one for printed messages.
- On each call, loop over every stored entry by index.
- If an entry has the same message and
timestamp - stored < 10, returnfalseimmediately. - If the loop finishes without a match, append the timestamp and message to the lists.
- Return
true.
Dry run
Start with empty lists. The first call, at timestamp 100 for the message unique, finds no entries, so the loop body never runs. The method appends (100, unique) to both lists and returns true, which gives the output [null, true].
For a longer check, feed the calls (1, foo), (2, bar), (3, foo), (11, foo). After the first two calls the lists hold times [1, 2] and messages [foo, bar]. The third call finds foo at time 1, and 3 - 1 = 2 is less than 10, so it returns false.
The fourth call finds foo at time 1, and 11 - 1 = 10 is not less than 10, so the scan continues and finds no other match. It appends (11, foo) and returns true.
Complexity
| Time | O(n) per call, O(n^2) for n calls |
|---|---|
| Space | O(n) |
Let n be the number of calls. The printed lists hold at most one entry per call, so a single call scans up to n entries with constant work per entry. Summing that work over n calls gives at most n times n steps, which is O(n^2). The lists store one entry per printed call, so the space is O(n).
PythonTested in our runner
class Logger:
def __init__(self):
# Printed calls only, stored as parallel lists
self.times = []
self.messages = []
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
# Scan every printed call, including ones for other messages
for i in range(len(self.messages)):
if self.messages[i] == message and timestamp - self.times[i] < 10:
return False
self.times.append(timestamp)
self.messages.append(message)
return TrueJavaTested in our runner
import java.util.*;
class Logger {
private List<Integer> times;
private List<String> messages;
public Logger() {
times = new ArrayList<>();
messages = new ArrayList<>();
}
public boolean shouldPrintMessage(int timestamp, String message) {
for (int i = 0; i < messages.size(); i++) {
// equals compares contents; == would compare references
if (messages.get(i).equals(message) && timestamp - times.get(i) < 10) {
return false;
}
}
times.add(timestamp);
messages.add(message);
return true;
}
}C++Tested in our runner
#include <vector>
#include <string>
#include <unordered_map>
#include <utility>
using namespace std;
class Logger {
private:
vector<pair<int, string>> printed; // (timestamp, message) of printed calls
public:
Logger() {}
bool shouldPrintMessage(int timestamp, string message) {
for (const auto& p : printed) {
if (p.second == message && timestamp - p.first < 10) return false;
}
printed.push_back({timestamp, message});
return true;
}
};JavaScriptTested in our runner
var Logger = function() {
// Printed calls only, stored as parallel arrays
this.times = [];
this.messages = [];
};
/**
* @param {number} timestamp
* @param {string} message
* @return {boolean}
*/
Logger.prototype.shouldPrintMessage = function(timestamp, message) {
for (let i = 0; i < this.messages.length; i++) {
if (this.messages[i] === message && timestamp - this.times[i] < 10) {
return false;
}
}
this.times.push(timestamp);
this.messages.push(message);
return true;
};GoTested in our runner
type Logger struct {
times []int
messages []string
}
func Constructor() Logger {
return Logger{}
}
func (this *Logger) shouldPrintMessage(timestamp int, message string) bool {
for i := range this.messages {
if this.messages[i] == message && timestamp-this.times[i] < 10 {
return false
}
}
this.times = append(this.times, timestamp)
this.messages = append(this.messages, message)
return true
}C#Tested in our runner
public class Logger {
private List<int> times = new List<int>();
private List<string> messages = new List<string>();
public Logger() {
}
public bool shouldPrintMessage(int timestamp, string message) {
for (int i = 0; i < messages.Count; i++) {
if (messages[i] == message && timestamp - times[i] < 10) {
return false;
}
}
times.Add(timestamp);
messages.Add(message);
return true;
}
}The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: One-pass hash map of last print timeOptimalDesign (General/Specific)
What is slow in the first approach is the scan. Each call reads entries for other messages and for prints that expired long ago, and none of those can change the answer. The insight that fixes it is that only the latest print of a message matters. Timestamps never decrease, so an older print is always further back than the newest one.
Store one number per message: its last printed timestamp. A hash map returns that number for a message in expected constant time. Rejected calls leave the map alone, so the stored time always belongs to a real print.
Steps
- In the constructor, create an empty hash map from message to last printed timestamp.
- On each call, look up
messagein the map. - If the message is present and
timestamp - last < 10, returnfalseand leave the map unchanged. - Otherwise set
map[message] = timestampand returntrue.
Dry run
The verified example has one printing call, so the trace is short. The table has one row for each step.
| Step | Action | Map before | Decision | Map after |
|---|---|---|---|---|
| 1 | Logger() creates the map | {} | none | {} |
| 2 | shouldPrintMessage(100, unique) | {} | unique is missing, so print | {unique: 100} |
The output is [null, true].
For a longer check, use the calls (1, foo), (2, bar), (3, foo), (11, foo).
| Call | Map before | Check | Decision | Map after |
|---|---|---|---|---|
| (1, foo) | {} | foo missing | true | {foo: 1} |
| (2, bar) | {foo: 1} | bar missing | true | {foo: 1, bar: 2} |
| (3, foo) | {foo: 1, bar: 2} | 3 - 1 = 2, less than 10 | false | {foo: 1, bar: 2} |
| (11, foo) | {foo: 1, bar: 2} | 11 - 1 = 10, not less than 10 | true | {foo: 11, bar: 2} |
Complexity
| Time | O(1) expected per call, O(n) for n calls |
|---|---|
| Space | O(n) |
Let n be the number of calls. Each call does one map lookup and at most one map write, and hashing a message reads at most 30 characters, so each operation is constant. The total work is therefore O(n). The map keeps at most one entry per distinct message, and there are at most n distinct messages, so the space is O(n).
PythonTested in our runner
class Logger:
def __init__(self):
# Maps each message to the timestamp of its last print
self.last_printed = {}
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
# Reject only if the last print is less than 10 seconds old
if message in self.last_printed and timestamp - self.last_printed[message] < 10:
return False
self.last_printed[message] = timestamp
return TrueJavaTested in our runner
import java.util.*;
class Logger {
// Maps each message to the timestamp of its last print
private Map<String, Integer> lastPrinted;
public Logger() {
lastPrinted = new HashMap<>();
}
public boolean shouldPrintMessage(int timestamp, String message) {
Integer last = lastPrinted.get(message);
if (last != null && timestamp - last < 10) {
return false;
}
lastPrinted.put(message, timestamp);
return true;
}
}C++Tested in our runner
#include <vector>
#include <string>
#include <unordered_map>
#include <utility>
using namespace std;
class Logger {
private:
unordered_map<string, int> lastPrinted; // message -> last printed timestamp
public:
Logger() {}
bool shouldPrintMessage(int timestamp, string message) {
auto it = lastPrinted.find(message);
if (it != lastPrinted.end() && timestamp - it->second < 10) return false;
lastPrinted[message] = timestamp;
return true;
}
};JavaScriptTested in our runner
var Logger = function() {
// Maps each message to the timestamp of its last print
this.lastPrinted = new Map();
};
/**
* @param {number} timestamp
* @param {string} message
* @return {boolean}
*/
Logger.prototype.shouldPrintMessage = function(timestamp, message) {
if (this.lastPrinted.has(message) && timestamp - this.lastPrinted.get(message) < 10) {
return false;
}
this.lastPrinted.set(message, timestamp);
return true;
};GoTested in our runner
type Logger struct {
lastPrinted map[string]int
}
func Constructor() Logger {
return Logger{lastPrinted: make(map[string]int)}
}
func (this *Logger) shouldPrintMessage(timestamp int, message string) bool {
if last, ok := this.lastPrinted[message]; ok && timestamp-last < 10 {
return false
}
this.lastPrinted[message] = timestamp
return true
}C#Tested in our runner
public class Logger {
// Maps each message to the timestamp of its last print
private Dictionary<string, int> lastPrinted = new Dictionary<string, int>();
public Logger() {
}
public bool shouldPrintMessage(int timestamp, string message) {
if (lastPrinted.TryGetValue(message, out int last) && timestamp - last < 10) {
return false;
}
lastPrinted[message] = timestamp;
return true;
}
}Common mistakes
lastPrinted[message] = timestampwritten before the comparison. The check then reads the value it wrote and rejects the call. Compare first, and write only when the message prints.- Updating the map on rejected calls, for example
last[message] = timestampoutside theif. A message that arrives every 9 seconds would then never print, because each rejection pushes the window forward. Write only on the true branch. - Using
timestamp - last <= 10as the reject test. This blocks a message exactly 10 seconds after its last print, which the rule allows. Reject only when the difference is strictly less than 10. - Appending rejected calls to the brute-force history. A rejected call then acts as a print. If foo prints at 1, is rejected at 5, and is called at 11, the stale entry at 5 blocks a valid print. Append only printed calls.
- Comparing Java strings with
==. That compares object references, so equal messages can look different. Useequals.
Edge cases
- First call for any message: nothing is stored yet, so the answer is
true. - Same message 9 seconds after its last print: the difference is 9, which is less than 10, so the answer is
false. - Same message exactly 10 seconds after its last print: the difference is 10, so the answer is
true. - Two different messages at the same timestamp: both return
true, because their keys differ. - Repeated calls at timestamp 0 for one message: the first returns
trueand the rest returnfalse. - Timestamps near 10^9 with 10^4 calls: the differences stay small and the optimal code never adds to a timestamp, so nothing overflows.
- Messages that differ only by case, such as
Helloandhello: they are different strings, so each one tracks its own last print.
Follow-ups interviewers ask
- What if timestamps can arrive out of order?
- The single last-print value breaks, because a late call can fall before a stored print. Keep a sorted list of printed timestamps for each message instead. For a call at time t, binary search for the nearest printed times on each side and reject if either is within 9 seconds. Each check costs O(log k), where k is the number of prints for that message. Inserting into a sorted array costs O(k), or you can use a balanced tree.
- Can the logger forget old messages to save memory?
- Yes. Keep a queue of (timestamp, message) pairs in the order they printed. On each call, pop from the front while the front entry is 10 or more seconds old. Delete the map entry only if it still holds the popped timestamp, because a newer print may have replaced it. Every pair is pushed and popped once, so the cleanup is amortized O(1) per call.
- What if the stream is too large for one machine?
- Shard the state by a hash of the message, so each shard owns a set of keys. Store the last print time in a key-value store, with an expiry of 10 seconds so old keys delete themselves. The check and the write must happen as one atomic compare-and-set. Otherwise two servers can both print the same message.
Logger Rate Limiter FAQ
What is the time complexity of Logger Rate Limiter?
The hash map version does O(1) expected work per call, so n calls take O(n) total. The brute force scan does O(n) work per call and O(n^2) total. Both use O(n) space in the worst case.
Why use a hash map for Logger Rate Limiter?
Each decision needs one number for one message, its last printed time. A hash map finds that number by message in expected constant time. A list scan would revisit prints that can no longer block anything.
Can Logger Rate Limiter be solved in O(1) extra space?
No, not in general. The answer for a message depends on its last print time, so you must remember that time for every distinct message that can come back. With up to 10^4 calls, that can mean up to 10^4 stored entries. Space can drop only with eviction, which keeps entries for the last 10 seconds.
Is a message allowed exactly 10 seconds after its last print?
Yes. The rule rejects only when the difference is less than 10, so a gap of exactly 10 prints.
Does the map need cleanup for this problem?
Not for the LeetCode version, because the input has at most 10^4 calls. A long-running logger should evict entries older than 10 seconds, as described in the follow-ups.
Asked at
See which companies ask this — Pro
Related problems
- Design HashMap · same technique: Design (General/Specific)
- Implement Queue using Stacks · same technique: Design (General/Specific)
- Implement Stack using Queues · same technique: Design (General/Specific)
- Moving Average from Data Stream · same technique: Design (General/Specific)
- Design Compressed String Iterator · same technique: Design (General/Specific)
- LRU Cache · next harder, same pattern
- Longest Word in Dictionary · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns
- Encode and Decode Strings · same pattern: Design Patterns