Rolling hit counter (time/space optimized)
Design a data structure that records events (“hits”) and can return how many hits happened in the most recent 300 seconds.
Implement two operations:
-
hit(t)
: record a hit at integer timestamp
t
(seconds).
-
getHits(t)
: return the number of hits with timestamps in the inclusive range
[t-299, t]
.
Assumptions / requirements
-
Timestamps are non-decreasing across calls.
-
Multiple hits may occur at the same timestamp.
-
You should optimize for time and space (avoid storing every hit individually if many occur at the same second).
Output
Return correct counts for each getHits query.
Complexity discussion
Be prepared to justify the time/space complexity of your approach and how it behaves under very high hit volume.