Design Hit Counter — Queue with Timestamp Expiry

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 295 · Design Hit Counter

Difficulty: Hard · Pattern: Queue with Expiry

Count hits in the past 300 seconds.

Solutions

# Python — queue (each hit stored)
from collections import deque
class HitCounter:
    def __init__(self): self.q = deque()
    def hit(self, timestamp): self.q.append(timestamp)
    def getHits(self, timestamp):
        while self.q and self.q[0] <= timestamp-300:
            self.q.popleft()
        return len(self.q)
# Python — bucketed (fixed 300 slots, O(1) space)
class HitCounter:
    def __init__(self):
        self.times = [0]*300
        self.hits = [0]*300
    def hit(self, timestamp):
        i = timestamp % 300
        if self.times[i] != timestamp:
            self.times[i] = timestamp; self.hits[i] = 0
        self.hits[i] += 1
    def getHits(self, timestamp):
        return sum(self.hits[i] for i in range(300) if timestamp-self.times[i] < 300)
// Java — bucketed
class HitCounter {
    int[] times=new int[300], hits=new int[300];
    public void hit(int t) { int i=t%300; if(times[i]!=t){times[i]=t;hits[i]=0;} hits[i]++; }
    public int getHits(int t) { int sum=0; for(int i=0;i<300;i++) if(t-times[i]<300) sum+=hits[i]; return sum; }
}

Complexity

  • Bucketed: O(1) hit, O(300) = O(1) getHits
  • Space: O(300) = O(1)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro