Design Hit Counter
Count events inside a rolling 5-minute window — the classic “design a hit counter”, made deterministic with logical timestamps.
Requirements
- A hit at time
his counted bygetHits(t)whent - 300 < h ≤ t— a half-open window: the point exactly 300 units old has already fallen out. - Timestamps are non-decreasing across the whole command stream (every
hitandgetHitsis at a time ≥ all earlier ones). Never read a real clock — time is the argument. - Multiple hits may occur at the same timestamp, and
getHitsmay be called when no hit is in range (return0). - Because time only moves forward, a hit that has expired for one query is expired for every later one — you may drop it permanently.
API to implement
Implement the class HitCounter. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.
| Command | Returns | Behavior |
|---|---|---|
| hit <timestamp> | — | Record one hit at timestamp. Several hits may share a timestamp. |
| getHits <timestamp> | int | Return the number of hits in the trailing window (timestamp - 300, timestamp] — the last 300 time units, expiry endpoint excluded. |
Input format
The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.
Output format
For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.
This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.
Sample cases
5
getHits 1
hit 1
getHits 1
getHits 300
getHits 3010
1
1
07
hit 1
hit 2
hit 3
getHits 4
getHits 300
getHits 301
getHits 3023
3
2
1