Taro Logo

Design Hit Counter

Medium
Uber logo
Uber
8 views
Topics:
Arrays

Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds). Each hit is recorded with a timestamp that is an integer representing seconds elapsed since the beginning of time.

You should implement the following methods:

  • HitCounter() Initializes the object of the hit counter system.
  • void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several hits may occur at the same same timestamp.
  • int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).

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]

Explanation
HitCounter hitCounter = new HitCounter();
hitCounter.hit(1);       // hit at timestamp 1.
hitCounter.hit(2);       // hit at timestamp 2.
hitCounter.hit(3);       // hit at timestamp 3.
hitCounter.getHits(4);   // get hits at timestamp 4, return 3.
hitCounter.hit(300);     // hit at timestamp 300.
hitCounter.getHits(300);  // get hits at timestamp 300, return 4.
hitCounter.getHits(301);  // get hits at timestamp 301, return 3.

Constraints:

  • 1 <= timestamp <= 2 * 109
  • All the calls are being made to the methods in chronological order (i.e., timestamp is monotonically increasing).
  • At most 300 calls will be made to hit and getHits.

Solution