Search
⌘K

Leetcode 359. Logger Rate Limiter

Asked at:

Google

Google

Amazon

Amazon


DESCRIPTION

Design a logger system that enforces a 10-second rate limit per unique message. The shouldPrintMessage(timestamp, message) method should return true if the message hasn't been printed in the last 10 seconds, otherwise false. For example, if "foo" is logged at timestamp 1, it can't be logged again until timestamp 11 or later.

Input:

shouldPrintMessage(1, "foo") → true
shouldPrintMessage(2, "bar") → true
shouldPrintMessage(3, "foo") → false
shouldPrintMessage(8, "bar") → false
shouldPrintMessage(10, "foo") → false
shouldPrintMessage(11, "foo") → true

Output:

true, true, false, false, false, true


Explanation: "foo" at timestamp 1 blocks until 11. "bar" at timestamp 2 blocks until 12. Requests within the 10-second window return false.

Constraints:

  • Timestamps are in seconds and arrive in chronological order
  • Multiple unique messages can be tracked simultaneously
  • Each message has an independent 10-second window

Understanding the Problem

The core challenge is tracking the last printed timestamp for each unique message. When a message arrives, we must check if current_timestamp - last_printed_timestamp >= 10. A hash map provides O(1) lookup and update for each message. The key insight is that we only need to store the most recent timestamp per message, not the entire history.

Building Intuition

A naive approach might store all timestamps for each message and scan the list to find recent entries, resulting in O(n) time per query. The optimal approach recognizes that we only care about the last printed time: if 10+ seconds have passed since then, we can print again. Using a Map<String, Integer> to store message → last_timestamp gives O(1) lookups. For example, if "foo" was last printed at timestamp 5, any request before timestamp 15 should return false.

Rate limiting is fundamental to API throttling, spam prevention, and log aggregation systems. This pattern appears in distributed systems (preventing duplicate alerts), chat applications (anti-spam), and monitoring tools (reducing log noise). Understanding fixed-window rate limiting is the foundation for more advanced techniques like sliding windows and token buckets.

Common Pitfalls

Implementation

Core Data Structure and Initialization

Create a hash map to store the mapping from each message to its last printed timestamp. Initialize the map in the constructor to prepare for tracking multiple messages. This structure provides O(1) access for both checking and updating timestamps. For example, after printing "foo" at timestamp 5, the map contains {"foo": 5}.

Solution
class Logger:
def __init__(self):
self.message_timestamps = {}
Message Rate Limiting Logic

Implement the shouldPrintMessage method that uses the map from Section 1. Check if the message exists in the map: if not present, return true and add it with the current timestamp. If present, calculate the time difference: return true and update the timestamp if >= 10 seconds have passed, otherwise return false. For example, if "foo" was last printed at timestamp 3, a request at timestamp 12 returns true and updates the map to {"foo": 12}.

Solution
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
if message not in self.message_timestamps:
self.message_timestamps[message] = timestamp
return True
time_diff = timestamp - self.message_timestamps[message]
if time_diff >= 10:
self.message_timestamps[message] = timestamp
return True
return False

What We've Learned

  • Pattern: Use a hash map to track per-message state for O(1) rate limit checks
  • Use Case: Fixed-window rate limiting for logging systems, API throttling, and spam prevention
  • Optimization: Only store the last timestamp per message, not the full history
  • Edge Case: Always allow first-time messages by checking map containment before time validation

Problems to Practice

Overview
Lesson
Sliding Window

The Logger Rate Limiter uses a fixed time window (10 seconds) to track message eligibility, which is conceptually similar to fixed-length sliding window problems. This lesson teaches how to maintain state over fixed intervals, a pattern directly applicable to rate limiting.

This problem requires tracking seen characters in a hashmap and managing a window of valid elements, similar to how the logger tracks messages and their timestamps. Both problems use hashmaps to maintain state and make decisions based on previously seen data.

Subarray Sum Equals K

medium

Prefix Sum

While focused on prefix sums, this problem heavily relies on hashmap usage to track cumulative values and make O(1) lookups, which is the same core technique used in the Logger Rate Limiter to track message timestamps and enforce the time window constraint.

Question Timeline

See when this question was last asked and where, including any notes left by other candidates.

Early September, 2025

Amazon

Amazon

Mid-level

Mid June, 2025

Amazon

Amazon

Mid-level

technical assessment question

Early May, 2025

Amazon

Amazon

Junior

Comments

Your account is free and you can post anonymously if you choose.