Community Problem

Design Hit Counter

Difficulty: Medium

Build a counter that returns the number of hits in the past 5 minutes (300 seconds), with monotonically non-decreasing timestamps.

Design Hit Counter

Build a counter that returns the number of hits in the past 5 minutes (300 seconds), with monotonically non-decreasing timestamps.

MEDIUM
Free
sliding-window
deque
arrays
meibennett

By @meibennett

January 4, 2026

·

Updated May 18, 2026

929 views

29

4.3 (13)

I had this on a Datadog backend onsite, in a round that doubled as the system-design warm-up. The interviewer cared about two things: (1) you handle the monotonic-timestamps assumption explicitly and (2) your getHits runs in time proportional to the WINDOW size, not the total history. The textbook answer is a deque (or circular buffer) of (timestamp, count) buckets, evicting anything older than 300 seconds.

Design Hit Counter

Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).

Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically non-decreasing). Several hits may arrive roughly at the same time.

Implement the HitCounter class:

  • 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 happen at the same timestamp.
  • int getHits(int timestamp) returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).

The past 5 minutes window is the half-open interval (timestamp - 300, timestamp].

Examples

Example 1:

HitCounter c = new HitCounter();
c.hit(1);            // hit at timestamp 1
c.hit(2);            // hit at timestamp 2
c.hit(3);            // hit at timestamp 3
c.getHits(4);        // 3 (hits 1, 2, 3 are within the window)
c.hit(300);          // hit at timestamp 300
c.getHits(300);      // 4 (hits 1, 2, 3, 300, all within (0, 300])
c.getHits(301);      // 3 (hit at 1 is now outside (1, 301])

Constraints

  • 1 <= timestamp <= 2 * 10^9.
  • All calls are made in chronological order (i.e., timestamp is non-decreasing).
  • At most 300 calls will be made to hit and getHits.

Follow-up

What if the number of hits per second could be very large? Compress consecutive hits at the same timestamp into a single (timestamp, count) bucket; the deque length is at most one entry per distinct second within the window (300 entries).

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems