15% off all plans & roadmaps Use code
See plansDesign Hit Counter
- LeetCode 362
- Medium
- Design Patterns
- Design (General/Specific)
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 giventimestamp, 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
hitandgetHits. - 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 - 299does not overflow in Java, C++ or C#.
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.
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
- Create an empty list of hit timestamps.
- In
hit, append the timestamp to the list. - In
getHits, start a counter at 0. - For each stored timestamp, add 1 when it lies in
[timestamp - 299, timestamp]. - 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
| Time | O(N) per getHits, O(1) per hit |
|---|---|
| Space | O(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 countJavaTested in our runner
import java.util.*;
class HitCounter {
private List<Integer> hitList;
public HitCounter() {
hitList = new ArrayList<>();
}
public void hit(int timestamp) {
hitList.add(timestamp);
}
public int getHits(int timestamp) {
int count = 0;
for (int t : hitList) {
if (t >= timestamp - 299 && t <= timestamp) {
count++;
}
}
return count;
}
}C++Tested in our runner
class HitCounter {
std::vector<int> hitList;
public:
HitCounter() {
}
void hit(int timestamp) {
hitList.push_back(timestamp);
}
int getHits(int timestamp) {
int count = 0;
for (int t : hitList) {
if (t >= timestamp - 299 && t <= timestamp) {
count++;
}
}
return count;
}
};JavaScriptTested in our runner
var HitCounter = function() {
this.hitList = [];
};
HitCounter.prototype.hit = function(timestamp) {
this.hitList.push(timestamp);
};
HitCounter.prototype.getHits = function(timestamp) {
let count = 0;
for (const t of this.hitList) {
if (t >= timestamp - 299 && t <= timestamp) {
count++;
}
}
return count;
};GoTested in our runner
type HitCounter struct {
hitList []int
}
func Constructor() HitCounter {
return HitCounter{hitList: []int{}}
}
func (this *HitCounter) hit(timestamp int) {
this.hitList = append(this.hitList, timestamp)
}
func (this *HitCounter) getHits(timestamp int) int {
count := 0
for _, t := range this.hitList {
if t >= timestamp-299 && t <= timestamp {
count++
}
}
return count
}C#Tested in our runner
public class HitCounter {
private List<int> hitList = new List<int>();
public HitCounter() {
}
public void hit(int timestamp) {
hitList.Add(timestamp);
}
public int getHits(int timestamp) {
int count = 0;
foreach (int t in hitList) {
if (t >= timestamp - 299 && t <= timestamp) {
count++;
}
}
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
- Create an empty deque named
window. - In
hit, push the timestamp onto the back. - In
getHits, pop from the front while the front is less thantimestamp - 299. - 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
| Time | O(1) amortized per call |
|---|---|
| Space | O(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)JavaTested in our runner
import java.util.*;
class HitCounter {
private Deque<Integer> window;
public HitCounter() {
window = new ArrayDeque<>();
}
public void hit(int timestamp) {
window.addLast(timestamp);
}
public int getHits(int timestamp) {
// expired hits sit at the front
while (!window.isEmpty() && window.peekFirst() < timestamp - 299) {
window.pollFirst();
}
return window.size();
}
}C++Tested in our runner
class HitCounter {
std::deque<int> window;
public:
HitCounter() {
}
void hit(int timestamp) {
window.push_back(timestamp);
}
int getHits(int timestamp) {
while (!window.empty() && window.front() < timestamp - 299) {
window.pop_front();
}
return (int)window.size();
}
};JavaScriptTested in our runner
var HitCounter = function() {
this.window = [];
this.head = 0;
};
HitCounter.prototype.hit = function(timestamp) {
this.window.push(timestamp);
};
HitCounter.prototype.getHits = function(timestamp) {
// head marks the first hit still inside the window
while (this.head < this.window.length && this.window[this.head] < timestamp - 299) {
this.head++;
}
return this.window.length - this.head;
};GoTested in our runner
type HitCounter struct {
window []int
head int
}
func Constructor() HitCounter {
return HitCounter{window: []int{}, head: 0}
}
func (this *HitCounter) hit(timestamp int) {
this.window = append(this.window, timestamp)
}
func (this *HitCounter) getHits(timestamp int) int {
for this.head < len(this.window) && this.window[this.head] < timestamp-299 {
this.head++
}
return len(this.window) - this.head
}C#Tested in our runner
public class HitCounter {
private Queue<int> window = new Queue<int>();
public HitCounter() {
}
public void hit(int timestamp) {
window.Enqueue(timestamp);
}
public int getHits(int timestamp) {
while (window.Count > 0 && window.Peek() < timestamp - 299) {
window.Dequeue();
}
return window.Count;
}
}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 infographicSolution 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
- Create two arrays,
timesandhits, of length 300, filled with 0. - In
hit, computei = timestamp % 300. - If
times[i]equalstimestamp, add 1 tohits[i]. Otherwise settimes[i] = timestampandhits[i] = 1. - In
getHits, loop over all 300 slots and addhits[i]whentimes[i] >= timestamp - 299. - Return the total.
Dry run
The example stops at 0, so trace it first with the state of both arrays.
| Step | Call | Slot change | Return |
|---|---|---|---|
| 1 | HitCounter() | times and hits are 300 zeros each | none |
| 2 | getHits(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 0 | 0 |
The example records no hits, so this second run shows the slots filling.
| Step | Call | Slot change | Return |
|---|---|---|---|
| 1 | hit(1) | i = 1 % 300 = 1. times[1] is 0, not 1, so times[1] = 1 and hits[1] = 1 | none |
| 2 | hit(1) | i = 1. times[1] is already 1, so hits[1] = 2 | none |
| 3 | hit(300) | i = 300 % 300 = 0. times[0] is 0, not 300, so times[0] = 300 and hits[0] = 1 | none |
| 4 | getHits(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 skipped | 3 |
Complexity
| Time | O(1) per call, since the scan covers a fixed 300 slots |
|---|---|
| Space | O(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 totalJavaTested in our runner
class HitCounter {
private int[] times;
private int[] hits;
public HitCounter() {
times = new int[300];
hits = new int[300];
}
public void hit(int timestamp) {
int i = timestamp % 300;
if (times[i] == timestamp) {
hits[i]++;
} else {
// the stored second is expired or unused, so overwrite it
times[i] = timestamp;
hits[i] = 1;
}
}
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < 300; i++) {
if (times[i] >= timestamp - 299) {
total += hits[i];
}
}
return total;
}
}C++Tested in our runner
class HitCounter {
std::vector<int> times;
std::vector<int> hits;
public:
HitCounter() : times(300, 0), hits(300, 0) {
}
void hit(int timestamp) {
int i = timestamp % 300;
if (times[i] == timestamp) {
hits[i]++;
} else {
times[i] = timestamp;
hits[i] = 1;
}
}
int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < 300; ++i) {
if (times[i] >= timestamp - 299) {
total += hits[i];
}
}
return total;
}
};JavaScriptTested in our runner
var HitCounter = function() {
this.times = new Array(300).fill(0);
this.hits = new Array(300).fill(0);
};
HitCounter.prototype.hit = function(timestamp) {
const i = timestamp % 300;
if (this.times[i] === timestamp) {
this.hits[i]++;
} else {
this.times[i] = timestamp;
this.hits[i] = 1;
}
};
HitCounter.prototype.getHits = function(timestamp) {
let total = 0;
for (let i = 0; i < 300; i++) {
if (this.times[i] >= timestamp - 299) {
total += this.hits[i];
}
}
return total;
};GoTested in our runner
type HitCounter struct {
times [300]int
hits [300]int
}
func Constructor() HitCounter {
return HitCounter{}
}
func (this *HitCounter) hit(timestamp int) {
i := timestamp % 300
if this.times[i] == timestamp {
this.hits[i]++
} else {
this.times[i] = timestamp
this.hits[i] = 1
}
}
func (this *HitCounter) getHits(timestamp int) int {
total := 0
for i := 0; i < 300; i++ {
if this.times[i] >= timestamp-299 {
total += this.hits[i]
}
}
return total
}C#Tested in our runner
public class HitCounter {
private int[] times = new int[300];
private int[] hits = new int[300];
public HitCounter() {
}
public void hit(int timestamp) {
int i = timestamp % 300;
if (times[i] == timestamp) {
hits[i]++;
} else {
times[i] = timestamp;
hits[i] = 1;
}
}
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < 300; i++) {
if (times[i] >= timestamp - 299) {
total += hits[i];
}
}
return total;
}
}Common mistakes
hits[i] += 1in the mismatch branch. When the slot holds an older second, its count carries over and inflates the total. Reset withtimes[i] = timestampandhits[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
hitsingetHitswithout checkingtimes. Slots that were never overwritten still hold old counts. Each slot's time must be checked first. - Deque eviction with
<=, as inwindow[0] <= timestamp - 299. That removes hits at exactlytimestamp - 299, which still belong to the window. Use a strict<. - Evicting only in
hitand not ingetHits. 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), thengetHits(300)returns 1, andgetHits(301)returns 0, because second 1 is outside [2, 301]. - Two seconds with the same remainder:
hit(1),hit(301), thengetHits(301)returns 1. Second 1 is 300 seconds old and must not count. - Largest timestamp:
hit(2000000000)thengetHits(2000000000)returns 1. The second maps to slot 200, andtimestamp - 299does not overflow a 32-bit int. - Long quiet period:
hit(5)thengetHits(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.hitstays O(1), butgetHitsnow 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
getHitscounts the values betweentimestamp - 299andtimestampwith 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
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns