FrontendInterviews.dev

Loading problem…

67. Design Hit Counter

Easy•
Acceptance: 96.30%
•
🔓3/3 Pro unlocks today

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

Implement a HitCounter class with the following methods:

  • hit(timestamp): Record a hit at the given timestamp (in seconds)
  • getHits(timestamp): Return the number of hits in the past 5 minutes (300 seconds) from the given timestamp

Requirements

1. Basic Functionality

  • Track hits within a 300-second sliding window
  • Each hit is recorded at a specific timestamp
  • getHits should only count hits from (timestamp - 299) to timestamp (inclusive)

Example Usage

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

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • All timestamps are in seconds
  • Calls are in chronological order
  • getHits should return hits from [timestamp - 299, timestamp]