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
hc = HitCounter()
hc.hit(1); hc.hit(2); hc.hit(3)
assert hc.getHits(4) == 3
hc.hit(300)
assert hc.getHits(300) == 4 and hc.getHits(301) == 3
hc2 = HitCounter()
for _ in range(1000):
hc2.hit(1)
assert hc2.getHits(300) == 1000 and hc2.getHits(301) == 0
class HitCounter {
private final int[] times = new int[300], counts = new int[300]; // ring of one-second buckets
public void hit(int timestamp) {
int i = timestamp % 300;
if (times[i] != timestamp) { times[i] = timestamp; counts[i] = 0; }
counts[i]++;
}
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < 300; i++) if (timestamp - times[i] < 300) total += counts[i];
return total;
}
}
type HitCounter struct {
q [][2]int // (timestamp, hits), oldest first
total int
}
func Constructor() HitCounter {
return HitCounter{}
}
func (this *HitCounter) Hit(timestamp int) {
if n := len(this.q); n > 0 && this.q[n-1][0] == timestamp { // same second: one entry
this.q[n-1][1]++
} else {
this.q = append(this.q, [2]int{timestamp, 1})
}
this.total++
}
func (this *HitCounter) GetHits(timestamp int) int {
for len(this.q) > 0 && this.q[0][0] <= timestamp-300 { // older than 5 minutes
this.total -= this.q[0][1]
this.q = this.q[1:]
}
return this.total
}