Problem 267243 · easy · Level 02 Linear Data Structures

Sliding Window Hit Counter

queues · deque · class design

Design a class HitCounter that counts hits inside a sliding time window. Timestamps are integers and are passed in non-decreasing order across all calls.

  • HitCounter(window): create a counter whose window covers window consecutive timestamps.
  • hit(t): record one hit at time t.
  • count(t): return the number of hits with a timestamp in [t - window + 1, t].

Examples

Input:  ops  = ["HitCounter", "hit", "hit", "hit", "count", "count", "hit", "count", "count"]
        args = [[300], [1], [2], [3], [4], [300], [300], [300], [301]]
Output: [None, None, None, None, 3, 3, None, 4, 3]
Explanation: count(300) covers times 1..300 (four hits); count(301) covers 2..301, so the hit at 1 no longer counts.

Constraints

  • 1 <= window <= 10**9
  • At most 10**4 calls in total
  • Target: amortised O(1) per call

Goals

  • Store timestamps in a deque and evict from the front
  • Keep each operation amortised O(1)
Starting Python…