Logger Rate Limiter
Here’s a way to implement the Logger
class as described in the problem statement:
- Initialize a Dictionary: Keep a dictionary to store the messages along with the next allowed timestamp for each message.
- Check and Update the Timestamp: For each incoming message, check if it’s allowed based on the current timestamp, and update the timestamp accordingly.
Below is the code implementing these steps:
|
|
Explanation:
- The
message_time
dictionary keeps track of each unique message and the next allowed timestamp for printing that message. - If the message is new or its next allowed timestamp is less than or equal to the current timestamp, the method returns
true
, and the next allowed timestamp is updated. - If the current timestamp is less than the next allowed timestamp for that message, the method returns
false
.
The time complexity of this approach is (O(1)) for both insertion and lookup. The space complexity depends on the number of unique messages, so in the worst case, it’s (O(N)), where (N) is the number of unique messages.
|
|