⚡Flashcard Drill➔
NeetCode #19LC-359EasyArrays & Hashing
← Back to All Problems

#19 · #359 · Logger Rate Limiter(日志速率限制器)

📌 Problem Statement & Constraints

Design a logger that only prints a message if it has not been printed in the last 10 seconds. Implement shouldPrintMessage(timestamp, message). Timestamps are non-decreasing integers (seconds). Constraints: at most 10^4 calls, 1 <= timestamp <= 10^9.

💡 Core Algorithmic Approaches

  1. Keep a hash map from message to the last timestamp at which it was printed.
  2. On each call, look up the message. If it is absent, or the stored timestamp is at least 10 seconds old, allow the print and update the map.
  3. Otherwise suppress it and return false.
  4. The window is inclusive of exactly 10 seconds, so the condition is timestamp - last >= 10, not > 10.

💻 Benchmark Python3 Implementation

class Logger:
    def __init__(self):
        self.last = {}                     # message -> last printed timestamp

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        last = self.last.get(message)
        if last is None or timestamp - last >= 10:   # never seen, or window elapsed
            self.last[message] = timestamp
            return True
        return False

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1) per call: a single hash lookup and update.
💾 Space Complexity
O(k) where k is the number of distinct messages seen.

⚠️ Interview Pitfalls & Follow-ups

  • Using > 10 instead of >= 10: a message exactly 10 seconds later is allowed, since the window is 10 seconds long.
  • Storing a queue of all timestamps: unnecessary; only the most recent timestamp per message matters.
  • Assuming timestamps are strictly increasing: the statement says non-decreasing, so equal timestamps are possible and the same comparison handles them.
  • Updating the timestamp on a suppressed call: this would push the window forward and could starve a message indefinitely. Only update when the print is allowed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

日志速率限制器

请你设计一个日志系统,可以流式接收日志以及它的时间戳。实现 Logger 类: shouldPrintMessage(timestamp, message) 判断该消息是否应当被打印。规则:同一条消息在 10 秒 内最多打印一次。若可以打印返回 true 并记录时间戳;否则返回 false。时间戳是严格非递减的。约束:0 ≤ timestamp ≤ 10^9;1 ≤ message.length ≤ 30;最多调用 10^4 次 shouldPrintMessage。

核心要点

  • 哈希表记录上次打印时间(标准解) :维护 消息: 上次成功打印的时间戳 。
  • 判定逻辑 :若消息不在表中,或 timestamp - 上次时间戳 &gt;= 10 ,则打印并更新时间戳;否则拒绝。
  • 注意边界是 &gt;= 10 而非 &gt; 10 :题目说「10 秒内最多打印一次」,因此恰好间隔 10 秒时 允许 打印。
  • 是否清理过期条目 :时间戳非递减,因此可以额外维护一个队列按时间清理超过 10 秒的条目,把空间降到 O(活跃消息数)。但在 10^4 次调用的规模下,直接保留全部条目也完全可行。

常见陷阱

  • 边界写成 &gt; 10 :会导致恰好间隔 10 秒时被错误拒绝。题目语义是「10 秒内不重复」,因此 &gt;= 10 才允许。
  • 用消息的首次出现时间而非最近一次成功打印时间 :必须每次成功打印时都更新时间戳,否则连续多次调用会一直用最初的时间戳判断。
  • 误以为时间戳可能回退 :题目保证非递减,因此可以安全地只比较差值;若时间戳无序,则需要更复杂的数据结构。

参考实现

class Logger:
    def __init__(self):
        self.last = {}          # message -> 上次打印的时间戳

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        prev = self.last.get(message)
        if prev is None or timestamp - prev >= 10:   # 恰好 10 秒可以打印
            self.last[message] = timestamp
            return True
        return False