FrontendInterviews.dev

Loading problem…

67. Design Hit Counter

Easy•

Design a time-based hit counter tracking system.

Requirements

Implement

class HitCounter {
  hit(timestamp) {}
  getHits(timestamp) {}
}
  • hit(timestamp): Record a request event that occurred at the specified timestamp.
  • getHits(timestamp): Return the total hits recorded within the past 300 seconds.
  • The sliding window must consider bounds exactly 300 seconds long (specifically (timestamp - 300, timestamp]).

Edge Cases

  • Timestamps are guaranteed to be monotonic (delivered in chronological order).
  • Multiple hits can arrive at the exact same timestamp. Ensure your storage mechanism accurately supports concurrent counts.

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

  • All timestamps are mapped as integers in seconds.
  • Storage capability must efficiently handle high-frequency events without ballooning array structures per individual hit.
  • Lookup constraints must scale properly. `O(N)` scans across the entire history of the server per `.getHits()` will time out.
  • Timestamp range: 1 <= timestamp <= 2 * 10^9.
  • Chronological Guarantees: Calls arrive in strictly monotonic order.
Accepted27/29|Acceptance Rate93.1%