⚡Flashcard Drill➔
NeetCode #157LC-362MediumArrays & Hashing
← Back to All Problems

#157 · #362 · Design Hit Counter(敲击计数器)

📌 Problem Statement & Constraints

Design a hit counter that counts hits in the past 5 minutes (300 seconds). Implement hit(timestamp) and getHits(timestamp). Timestamps are non-decreasing. Constraints: 1 <= timestamp <= 10^9; at most 300 calls to hit.

💡 Core Algorithmic Approaches

  1. Keep a deque of hit timestamps. hit simply appends.
  2. getHits pops from the front while the oldest hit is outside the 300-second window.
  3. The window is (timestamp - 300, timestamp], so a hit exactly 300 seconds old is expired: the eviction condition is <= timestamp - 300.
  4. Each hit is appended once and popped at most once, so the total cost across all calls is O(number of hits).

💻 Benchmark Python3 Implementation

class HitCounter:
    def __init__(self):
        from collections import deque
        self.hits = deque()

    def hit(self, timestamp: int) -> None:
        self.hits.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        while self.hits and self.hits[0] <= timestamp - 300:
            self.hits.popleft()            # outside the 300-second window
        return len(self.hits)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1) amortised per call: each timestamp is appended once and evicted at most once.
💾 Space Complexity
O(number of hits within the window).

⚠️ Interview Pitfalls & Follow-ups

  • Using < timestamp - 300: a hit exactly 300 seconds old is outside the window, so the condition must be <=.
  • Storing counts per second in an array of size 300: a valid O(1)-space design (with modular indexing), but the deque is simpler and equally efficient at these limits.
  • Recomputing the count by scanning all stored hits: O(number of hits) per query, which defeats the deque.
  • Assuming timestamps are strictly increasing: they may repeat, and the deque handles that.
⚡
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

中文速览与面试要点

敲击计数器

设计一个敲击计数器,使它可以统计在过去 5 分钟(300 秒)内被敲击了多少次。实现 HitCounter 类: hit(timestamp) 表示在时刻 timestamp 有一次敲击; getHits(timestamp) 返回在时间范围 [timestamp − 300 + 1, timestamp] 内的敲击次数。约束:1 ≤ timestamp ≤ 10^9;所有对 hit 的调用都使用 严格递增 的 timestamp;最多调用 300 次。

核心要点

  • 双端队列 + 惰性清理(标准解) :用一个 deque 按时间顺序保存所有敲击时刻。
  • getHits 时清理过期项 :从队首不断弹出「 timestamp − 300 及更早」的敲击,剩下的即为窗口内的次数。
  • 为什么是 &lt;= timestamp − 300 而不是 &lt; :窗口是 [timestamp − 299, timestamp] ,共 300 个时刻,因此 timestamp − 300 已在窗口外。
  • 为什么可以永久弹出 :时间戳严格递增,过期的敲击永远不会再进入未来的窗口。
  • 均摊复杂度 :每次 hit 入队一次,每个元素最多出队一次,因此所有调用合计 O(n),单次均摊 O(1)。

常见陷阱

  • 窗口边界写成 &lt; timestamp - 300 :会多保留一个过期时刻,导致计数偏大。正确条件是 &lt;= timestamp - 300 。
  • 每次 getHits 都遍历整个队列过滤 :虽然逻辑正确,但若不清除过期项,队列会无限增长。必须用惰性弹出。
  • 用 list 而非 deque :list 的 pop(0) 是 O(n),会让均摊复杂度退化。
  • 误以为需要保存每一秒的计数 :本题规模小(≤ 300 次调用),deque 已足够;若调用量极大,可改用「按秒分桶 + 循环数组」把空间降到 O(300)。

参考实现

from collections import deque

class HitCounter:
    def __init__(self):
        self.q = deque()

    def hit(self, timestamp: int) -> None:
        self.q.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        # 窗口为 [timestamp-299, timestamp],故 timestamp-300 及更早的应移除
        while self.q and self.q[0] <= timestamp - 300:
            self.q.popleft()
        return len(self.q)