Design Hit Counter

medium design queue

Problem

Design a hit counter that supports hit(t) and getHits(t) returning the number of hits in the last 5 minutes (300s).

Inputhit(1), hit(2), hit(3), getHits(4), hit(300), getHits(300), getHits(301)
Output[3, 4, 3]
Hits older than t-300 are pruned.

from collections import deque
class HitCounter:
    def __init__(self):
        self.q = deque()
    def hit(self, t):
        self.q.append(t)
    def getHits(self, t):
        while self.q and self.q[0] <= t - 300:
            self.q.popleft()
        return len(self.q)
class HitCounter {
  constructor() { this.q = []; }
  hit(t) { this.q.push(t); }
  getHits(t) {
    while (this.q.length && this.q[0] <= t - 300) this.q.shift();
    return this.q.length;
  }
}
class HitCounter {
    Deque q = new ArrayDeque<>();
    public void hit(int t) { q.add(t); }
    public int getHits(int t) {
        while (!q.isEmpty() && q.peek() <= t - 300) q.poll();
        return q.size();
    }
}
class HitCounter {
    deque q;
public:
    void hit(int t) { q.push_back(t); }
    int getHits(int t) {
        while (!q.empty() && q.front() <= t - 300) q.pop_front();
        return q.size();
    }
};
Time: amortized O(1) Space: O(W)