SDE & MLE Prep

362. Design Hit Counter

Problem

Design HitCounter: hit(timestamp) records a hit at that second, and getHits(timestamp) returns the number of hits in the past 5 minutes (the 300 seconds up to and including timestamp). Timestamps never decrease, and several hits can share one timestamp.

Example: hits at 1, 2, 3 → getHits(4) = 3; hit at 300 → getHits(300) = 4, getHits(301) = 3

Constraints: follow-up: a huge number of hits per second.

Problem (Premium): hit(timestamp) records a hit (several may share a timestamp); getHits(timestamp) returns the hits in the past 5 minutes — timestamps in (t − 300, t]. Calls arrive in non-decreasing time order.

A queue of [timestamp, count] buckets (collapsing equal timestamps) plus a running total: expire buckets from the front on read. For huge hit rates, the follow-up answer is a fixed ring of 300 one-second buckets (times[t % 300], counts[t % 300]), O(300) memory regardless of traffic.

Complexity: amortized O(1) per call.

class HitCounter:
    def __init__(self):
        self.q = deque()          # [timestamp, count], oldest first
        self.total = 0

    def hit(self, timestamp: int) -> None:
        if self.q and self.q[-1][0] == timestamp:
            self.q[-1][1] += 1
        else:
            self.q.append([timestamp, 1])
        self.total += 1

    def getHits(self, timestamp: int) -> int:
        while self.q and self.q[0][0] <= timestamp - 300:
            self.total -= self.q.popleft()[1]
        return self.total