Programming & Development / April 10, 2025

LeetCode 359: Logger Rate Limiter – Simple HashMap Design

LeetCode 359 Logger Rate Limiter Python design question hashmap logging system system design rate limiting timestamps efficient lookup data structure

πŸ“˜ Problem Statement

Design a logger system that receives a stream of messages along with timestamps. Each message should only be printed if it was not printed in the last 10 seconds.

Implement the Logger class:

python

Logger():
    Initializes the logger object.

bool shouldPrintMessage(int timestamp, string message):
    Returns true if the message should be printed at the given timestamp,
    otherwise returns false.

Constraints:

  • All timestamps are in seconds and strictly increasing.
  • The timestamp is a positive integer up to 2^31 - 1.

🧠 Key Idea

We only need to remember the last printed timestamp of each message.

The ideal data structure is a hashmap that maps:

python

message β†’ last printed timestamp

Check if:

python

current_timestamp - last_timestamp >= 10

🐍 Python Code

python

class Logger:

    def __init__(self):
        self.msg_map = {}

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

πŸ” Step-by-Step Explanation

1. Initialize

python

self.msg_map = {}
  • Stores the last printed time for each unique message.

2. Check If Message Can Be Printed

python

if message not in self.msg_map or timestamp - self.msg_map[message] >= 10
  • If it’s a new message or the last time it was printed was β‰₯10 seconds ago, allow it.

3. Update Timestamp

python

self.msg_map[message] = timestamp
  • Record the latest time this message was printed.

4. Else Return False

πŸ’‘ Example Trace

python

logger = Logger()
logger.shouldPrintMessage(1, "foo")   # True
logger.shouldPrintMessage(2, "bar")   # True
logger.shouldPrintMessage(3, "foo")   # False
logger.shouldPrintMessage(10, "foo")  # False
logger.shouldPrintMessage(11, "foo")  # True

⏱️ Time & Space Complexity

OperationComplexityTimeO(1)SpaceO(n)

🧡 Final Thoughts

This is a perfect warm-up problem for:

  • Designing efficient key-value data structures
  • Implementing rate limiting logic
  • Practicing O(1) time complexity checks



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex