Design Hit Counter
Medium
Topics
Design a hit counter that counts hits received in the past 5 minutes (300 seconds). Implement HitCounter(), hit(timestamp) which records a hit at the given timestamp (in seconds), and getHits(timestamp) which returns the number of hits in the past 300 seconds — that is, hits with a recorded time in the range (timestamp - 300, timestamp]. Calls are made in non-decreasing time order.
Example 1
Every hit carries the second it happened. A query asks how many hits fall in the past 300 seconds counted back from the query’s own timestamp, so the window moves with each query and a hit that has aged out never counts again.
Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["HitCounter","hit","hit","hit","getHits","hit","getHits","getHits"], values = [[],[1],[2],[3],[4],[300],[300],[301]] Output: [null,null,null,null,3,null,4,3]
Constraints
- 1 <= timestamp <= 2*10^9
- All calls are made with non-decreasing timestamps.
- At most 300 calls per getHits window in the basic version.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Only hits within the trailing 300-second window matter. Since timestamps never decrease, older hits can be dropped from the front of a queue.
Approach
- Store hit timestamps in a queue in arrival order.
- On getHits(t), evict timestamps from the front that are <= t - 300.
- Return the queue size — the hits remaining in (t - 300, t].
Dry Run
HitCounter(). The queue holds raw timestamps; stale ones are dropped lazily, on
read rather than on write.
hit 1 queue [1]
hit 2 queue [1, 2]
hit 3 queue [1, 2, 3]
getHits 4 -> 3 cutoff 4 - 300 = -296, nothing is stale
hit 300 queue [1, 2, 3, 300]
getHits 300 -> 4 cutoff 0; the hit at 1 is NOT <= 0, so it stays
getHits 301 -> 3 cutoff 1; the hit at 1 IS <= 1, so it is dropped
answer null|null|null|3|null|4|3
The last two rows are the whole problem. The window is the last 300 seconds
INCLUSIVE of the current second, which means a hit at time t survives a query at
t + 299 and dies at t + 300. The eviction test is therefore `<= timestamp - 300`:
with strict `<`, the hit at 1 survives the query at 301 and the answer is 4
instead of 3 -- off by one, on one query.
Eviction happens in getHits, not in hit. Nothing expires until somebody asks,
which keeps hit O(1) and makes getHits amortised O(1): each timestamp is appended
once and dropped at most once.
At the stated scale this is fine, but the queue grows with the number of hits
rather than with the window. The usual refinement is 300 buckets of
(second, count), which bounds the memory regardless of hit rate -- worth naming
if asked about a high-traffic counter.Complexity
- Time — O(1) amortized: each timestamp is enqueued and evicted at most once.
- Space — O(w): the queue holds only hits inside the 300 s window.
Common Pitfalls
- The window excludes timestamp - 300, so evict hits with time <= t - 300.
Full Solution — all languages
class HitCounter:
def __init__(self):
from collections import deque
self.hits = deque()
def hit(self, timestamp):
self.hits.append(timestamp)
def getHits(self, timestamp):
while self.hits and self.hits[0] <= timestamp - 300:
self.hits.popleft()
return len(self.hits)import java.util.*;
class HitCounter {
private final Deque<Integer> hits = new ArrayDeque<>();
public HitCounter() {
}
public void hit(int timestamp) {
hits.addLast(timestamp);
}
public int getHits(int timestamp) {
while (!hits.isEmpty() && hits.peekFirst() <= timestamp - 300) hits.pollFirst();
return hits.size();
}
}#include <bits/stdc++.h>
using namespace std;
class HitCounter {
public: HitCounter() {
}
void hit(int timestamp) {
hits_.push_back(timestamp);
}
int getHits(int timestamp) {
while (!hits_.empty() && hits_.front() <= timestamp - 300) hits_.pop_front();
return (int)hits_.size();
}
private: deque<int> hits_;
};class HitCounter {
constructor() {
this.hits = [];
this.head = 0;
}
hit(timestamp) {
this.hits.push(timestamp);
}
getHits(timestamp) {
while (this.head < this.hits.length && this.hits[this.head] <= timestamp - 300) this.head++;
return this.hits.length - this.head;
}
}