15% off all plans & roadmaps Use code

See plans

Design Hit Counter

Updated

TL;DR: The counter must report how many hits landed in the last 300 seconds. Keep one count per second in 300 slots, indexed by the second modulo 300, so every call does constant work.

Problem

You are given a class HitCounter that records hits. Each hit happens at a timestamp, an integer number of seconds. Implement the following two methods.

  • hit(timestamp): records a hit at the given timestamp, which is the current time in seconds.
  • getHits(timestamp): returns the number of hits in the past 5 minutes, meaning hits in the interval [timestamp - 299, timestamp], inclusive.

Both methods receive timestamps in chronological order. Each new timestamp is greater than or equal to the timestamp of the previous call.

Return the number of hits in the past 5 minutes for each call to getHits.

Example 1

Input: operations = ["HitCounter", "getHits"], parameters = [[], [100]]
Output: [null, 0]

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • At most 300 calls will be made to hit and getHits.
  • Calls arrive in chronological order.

Constraints that matter

  • At most 300 calls means a list of 300 entries is cheap, so brute force is correct here. Its cost still grows with the number of recorded hits.
  • Timestamps never decrease, so the oldest hit is always at the front. Expired hits can be removed from that one end.
  • The window is 300 seconds, so at most 300 distinct seconds are live at once. A fixed array of 300 slots is enough to hold them.
  • Timestamps go up to 2 * 10^9, which is too large to use as array indexes. Map each second to a slot with modulo 300.
  • 2 * 10^9 fits in a 32-bit signed integer, so timestamp - 299 does not overflow in Java, C++ or C#.

View on LeetCode

Hints

Hint 1

This is a design problem, so start with the state the object must keep.

Hint 2

Record every hit timestamp in a list.

Solution

Intuition

This is a design problem, so start with the state the object must keep. Each call asks only about a sliding window of 300 seconds. A hit stops mattering once it falls out of that window, and timestamps never go backwards.

Picture a row of 300 numbered mailboxes reused on a repeating cycle. The box for second t is box t mod 300, and a new letter overwrites an old one that is already too old to matter.

Two facts point to a fixed-size structure. The window length is a constant, so at most 300 seconds are live at once. Many hits can also share one second, so a count per second is enough. Modulo arithmetic maps each second onto one of 300 slots.

Why this works: two seconds that are live together differ by less than 300, so they land in different slots. A slot that holds an older second is stale once a newer second with the same remainder arrives, because the old second is at least 300 seconds behind. The check in getHits skips any slot whose stored second is outside the window.

Watch the pattern animation

Worked example

Input: operations = ["HitCounter", "getHits"], parameters = [[], [100]]
Output: [null, 0]
Explanation: The counter is created, and then getHits(100) runs. No hit was recorded, so the count is 0. This example has no hits, so the dry runs below also use a second short sequence.

Approach 1: Brute force

Record every hit timestamp in a list. For getHits, scan the whole list and count the timestamps inside [timestamp - 299, timestamp]. This is correct because each stored hit is checked directly.

Every query rereads the full history, including hits that expired long ago. The cost grows with every hit ever recorded.

Steps

  1. Create an empty list of hit timestamps.
  2. In hit, append the timestamp to the list.
  3. In getHits, start a counter at 0.
  4. For each stored timestamp, add 1 when it lies in [timestamp - 299, timestamp].
  5. Return the counter.

Dry run

The example records no hits, so the list starts empty. getHits(100) loops over zero values, the counter stays at 0, and the method returns 0, which matches the example.

For a second check, run hit(1), hit(1), hit(300), then getHits(300). The list is [1, 1, 300]. All three values lie in [1, 300], so the answer is 3.

Complexity

TimeO(N) per getHits, O(1) per hit
SpaceO(N)

Let N be the number of hits recorded so far. hit appends to a list in constant time. getHits loops over all N stored values once with one comparison each, so it costs O(N). The list stores every timestamp, so the space is O(N).

PythonTested in our runner

from typing import List, Optional

class HitCounter:
    def __init__(self):
        self.hit_list = []

    def hit(self, timestamp: int) -> None:
        self.hit_list.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        count = 0
        for t in self.hit_list:
            # keep hits inside [timestamp - 299, timestamp]
            if timestamp - 299 <= t <= timestamp:
                count += 1
        return count

Approach 2: Queue with eviction

What's slow: the scan rereads hits that can never count again. Every old hit stays in the list and costs time on every query.

The insight: timestamps only grow, so the oldest hit always sits at the front of a queue. When a query arrives, pop expired hits from the front. What remains is exactly the window, and its size is the answer.

Steps

  1. Create an empty deque named window.
  2. In hit, push the timestamp onto the back.
  3. In getHits, pop from the front while the front is less than timestamp - 299.
  4. Return the number of entries left in the deque.

Dry run

The example again ends at 0. The deque is empty, the front check finds nothing to pop, and the size is 0.

For the second sequence, hit(1) gives [1], hit(1) gives [1, 1], and hit(300) gives [1, 1, 300]. getHits(300) has threshold 1, so nothing is popped and the size is 3. getHits(301) has threshold 2, so the two 1s are popped and the size is 1.

Complexity

TimeO(1) amortized per call
SpaceO(N), where N is the number of hits still in the window

Let N be the total number of hits recorded. Each hit is pushed once and popped at most once, so all eviction work across all calls is at most N. That gives O(1) amortized per call. A single getHits can pop many entries, so its worst case is O(N), and the deque holds at most one entry per live hit.

PythonTested in our runner

from typing import List, Optional
from collections import deque

class HitCounter:
    def __init__(self):
        self.window = deque()

    def hit(self, timestamp: int) -> None:
        self.window.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        # the oldest hits sit at the front, so drop the expired ones
        while self.window and self.window[0] < timestamp - 299:
            self.window.popleft()
        return len(self.window)

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 3: Circular time bucketsOptimalDesign (General/Specific)

What's slow: the queue keeps one entry per hit. A burst of 300 hits in one second takes 300 entries, even though one count would do.

The insight: the window covers 300 consecutive seconds, so at most 300 seconds are live at once. Map second t to slot t % 300 and store a time and a count in that slot. Two live seconds differ by less than 300, so they never share a slot.

Steps

  1. Create two arrays, times and hits, of length 300, filled with 0.
  2. In hit, compute i = timestamp % 300.
  3. If times[i] equals timestamp, add 1 to hits[i]. Otherwise set times[i] = timestamp and hits[i] = 1.
  4. In getHits, loop over all 300 slots and add hits[i] when times[i] >= timestamp - 299.
  5. Return the total.

Dry run

The example stops at 0, so trace it first with the state of both arrays.

StepCallSlot changeReturn
1HitCounter()times and hits are 300 zeros eachnone
2getHits(100)threshold is 100 - 299 = -199. All 300 slots have time 0, which is at least -199, so each adds its hits value of 0. Total stays 00

The example records no hits, so this second run shows the slots filling.

StepCallSlot changeReturn
1hit(1)i = 1 % 300 = 1. times[1] is 0, not 1, so times[1] = 1 and hits[1] = 1none
2hit(1)i = 1. times[1] is already 1, so hits[1] = 2none
3hit(300)i = 300 % 300 = 0. times[0] is 0, not 300, so times[0] = 300 and hits[0] = 1none
4getHits(300)threshold is 1. Slot 0 has time 300 and adds 1. Slot 1 has time 1 and adds 2. Other slots have time 0 and are skipped3

Complexity

TimeO(1) per call, since the scan covers a fixed 300 slots
SpaceO(1), two arrays of 300 integers

Let W be the window length, which is 300 here. hit computes one remainder, makes one comparison and writes at most two values, so it does constant work. getHits loops over W slots once, so it costs O(W), which is O(1) because W is fixed. Space is two arrays of W integers, so it does not grow with the number of hits.

PythonTested in our runner

from typing import List, Optional

class HitCounter:
    def __init__(self):
        self.times = [0] * 300
        self.hits = [0] * 300

    def hit(self, timestamp: int) -> None:
        i = timestamp % 300
        if self.times[i] == timestamp:
            self.hits[i] += 1
        else:
            # the stored second is expired or unused, so overwrite it
            self.times[i] = timestamp
            self.hits[i] = 1

    def getHits(self, timestamp: int) -> int:
        total = 0
        for i in range(300):
            if self.times[i] >= timestamp - 299:
                total += self.hits[i]
        return total

Common mistakes

  • hits[i] += 1 in the mismatch branch. When the slot holds an older second, its count carries over and inflates the total. Reset with times[i] = timestamp and hits[i] = 1.
  • Off-by-one window bound such as times[i] >= timestamp - 300. That counts one extra second. The window is [timestamp - 299, timestamp], so the bound uses 299.
  • Summing hits in getHits without checking times. Slots that were never overwritten still hold old counts. Each slot's time must be checked first.
  • Deque eviction with <=, as in window[0] <= timestamp - 299. That removes hits at exactly timestamp - 299, which still belong to the window. Use a strict <.
  • Evicting only in hit and not in getHits. After a quiet stretch, a query would count hits that have already expired. Evict on every query.

Edge cases

  • No hits, then getHits(1). Every approach returns 0. The bucket version sums slots that hold 0.
  • 300 hits all at timestamp 1, then getHits(300). The answer is 300. The bucket version stores one count for them.
  • Boundary: hit(1), then getHits(300) returns 1, and getHits(301) returns 0, because second 1 is outside [2, 301].
  • Two seconds with the same remainder: hit(1), hit(301), then getHits(301) returns 1. Second 1 is 300 seconds old and must not count.
  • Largest timestamp: hit(2000000000) then getHits(2000000000) returns 1. The second maps to slot 200, and timestamp - 299 does not overflow a 32-bit int.
  • Long quiet period: hit(5) then getHits(1000) returns 0, because 5 is below the bound 701.

Follow-ups interviewers ask

What if the window length W is a parameter instead of 300?
The bucket version still works with W slots and timestamp % W. hit stays O(1), but getHits now costs O(W) because it scans every slot. A deque of (time, count) pairs avoids that cost. Each pair is popped once, so calls cost O(1) amortized, and memory depends on the seconds that had hits.
What if timestamps can arrive out of order?
The bucket trick fails. An older timestamp can land in a slot that holds a newer second and overwrite its count. Keep a sorted list of timestamps instead. Each hit is inserted in order, and getHits counts the values between timestamp - 299 and timestamp with two binary searches. The insert costs O(log N) with a balanced tree, or O(N) with a plain array.
What if every user needs their own counter?
Keep a hash map from user id to a counter object. Memory then grows with the number of active users. A sparse user can use the (time, count) deque, which stores only seconds that had hits. A busy user can use the 300-slot array, which costs a fixed amount of memory.

Design Hit Counter FAQ

What is the time complexity of Design Hit Counter?

The bucket approach runs hit in O(1) and getHits in O(300), which is O(1) because the window is fixed. The queue approach runs in O(1) amortized per call. The brute force list costs O(N) per getHits, where N is the number of recorded hits.

Why use a fixed array of time buckets for Design Hit Counter?

The window is a fixed 300 seconds, so only 300 distinct seconds can be live at once. Modulo maps each second to one slot. A count in each slot also compresses many hits in the same second into one integer.

Can Design Hit Counter be solved in O(1) extra space?

Yes, for this problem. The bucket solution keeps 600 integers no matter how many hits arrive, because the window length is a fixed constant. If the window length W were a parameter, the space would be O(W), so O(1) would no longer hold.

Why is a queue of timestamps not constant space?

The queue keeps one entry per hit still in the window. A burst of 300 hits in one second takes 300 entries. With at most 300 calls this is fine, but the size grows with the number of hits.

Why check the stored time in getHits for the bucket approach?

A slot that was never overwritten still holds an old second and its count. Without the time check, those old counts would be added to the answer. The check times[i] >= timestamp - 299 filters them out.

Asked at

See which companies ask this — Pro

Practise it