Skip to content
Onsite

Design Hit Counter

MediumP2Coding

Design a counter of hits on a website over the past 5 minutes (300 seconds).

Implement the HitCounter class:

  • HitCounter() creates the counter.
  • hit(timestamp) records one hit at timestamp (in seconds).
  • getHits(timestamp) returns the number of hits in the window (timestamp - 300, timestamp], that is, hits at times timestamp - 299 up to timestamp.

Calls arrive in non-decreasing timestamp order; several hits may share a timestamp.

Example 1

Input
["HitCounter","hit","hit","hit","getHits","hit","getHits","getHits"] [[],[1],[2],[3],[4],[300],[300],[301]]
Output
[null,null,null,null,3,null,4,3]
Why
The hit at time 1 is inside the window ending at 300 but outside the one ending at 301.

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • Timestamps are non-decreasing.
  • At most 10^5 calls to hit and getHits in total.

Hints

Run checks the 2 visible tests, Submit all 7.