SDE Path

Design Hit Counter

Medium

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 h is counted by getHits(t) when t - 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 hit and getHits is at a time ≥ all earlier ones). Never read a real clock — time is the argument.
  • Multiple hits may occur at the same timestamp, and getHits may be called when no hit is in range (return 0).
  • 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

Example 1
Input
5
getHits 1
hit 1
getHits 1
getHits 300
getHits 301
Expected output
0
1
1
0
Example 2
Input
7
hit 1
hit 2
hit 3
getHits 4
getHits 300
getHits 301
getHits 302
Expected output
3
3
2
1