Design Hit Counter

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a hit counter that counts the number of hits received in the past 300 seconds.

Implement a function that processes an array of operations and an array of arguments:

  • "HitCounter" — Initializes the hit counter.
  • "hit" — Records a hit at the given timestamp (in seconds). Multiple hits may have the same timestamp.
  • "getHits" — Returns the number of hits in the past 300 seconds from timestamp (inclusive of timestamp - 299 to timestamp).

The timestamp values passed to hit and getHits are non-decreasing.

Examples

Example 1:

Input: operations = ["HitCounter","hit","hit","hit","getHits","hit","getHits","getHits"], args = [[],[1],[2],[3],[4],[300],[300],[301]]

Output: [null,null,null,null,3,null,4,3]

Explanation: Hits at t=1,2,3. getHits(4) counts hits in [1..4] → 3. Hit at t=300. getHits(300) counts [1..300] → 4. getHits(301) counts [2..301] → 3 (t=1 is now outside the 300s window).

Example 2:

Input: operations = ["HitCounter","hit","hit","getHits","getHits"], args = [[],[1],[1],[1],[300]]

Output: [null,null,null,2,2]

Explanation: Two hits at t=1. getHits(1) and getHits(300) both see both hits inside the 300s window.

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • All calls to hit and getHits are made in non-decreasing order of timestamp
  • At most 300 calls will be made to hit and getHits
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle