362. Design Hit Counter
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a HitCounter class that can log hits with timestamps and retrieve the number of hits that occurred in the last 5 minutes (300 seconds). A key constraint is that timestamps are always increasing. The follow-up question about handling a huge number of hits per second suggests that a memory-efficient and scalable solution is preferred.
Solution
Design Hit Counter in Python
class HitCounter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.window_size = 300 # 5 minutes in seconds
# timestamps[i] stores the timestamp of a hit that maps to bucket i
self.timestamps = [0] * self.window_size
# hits[i] stores the count of hits for the timestamp in timestamps[i]
self.hits = [0] * self.window_size
def hit(self, timestamp: int) -> None:
"""
Record a hit.
:param timestamp: The current timestamp (in seconds).
"""
# Map timestamp to a bucket index (0-299)
# We use (timestamp - 1) as timestamps are 1-based.
index = (timestamp - 1) % self.window_size
# If the timestamp in the bucket matches the current one,
# it's a hit in the same second.
if self.timestamps[index] == timestamp:
self.hits[index] += 1
else:
# Otherwise, this bucket is for a new second.
# Reset the timestamp and hit count for this bucket.
self.timestamps[index] = timestamp
self.hits[index] = 1
def getHits(self, timestamp: int) -> int:
"""
Return the number of hits in the past 5 minutes.
:param timestamp: The current timestamp (in seconds).
"""
total_hits = 0
# Iterate through all buckets to sum up recent hits.
for i in range(self.window_size):
# A hit is recent if its timestamp is within the last 300 seconds.
# The window is (timestamp - 300, timestamp].
if timestamp - self.timestamps[i] < self.window_size:
total_hits += self.hits[i]
return total_hits
# Your HitCounter object will be instantiated and called as such:
# obj = HitCounter()
# obj.hit(timestamp)
# param_2 = obj.getHits(timestamp)
Design Hit Counter in Java
class HitCounter {
private final int windowSize = 300; // 5 minutes = 300 seconds
private int[] timestamps;
private int[] hits;
/** Initialize your data structure here. */
public HitCounter() {
timestamps = new int[windowSize];
hits = new int[windowSize];
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds). */
public void hit(int timestamp) {
// Map the timestamp to an index in our circular arrays.
// We use (timestamp - 1) as timestamps are 1-based.
int index = (timestamp - 1) % windowSize;
// If the timestamp at this index matches the current timestamp,
// it's a hit within the same second.
if (timestamps[index] == timestamp) {
hits[index]++;
} else {
// If it's a different timestamp, it means this bucket is either
// new or being recycled for a new second. Reset the bucket.
timestamps[index] = timestamp;
hits[index] = 1;
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds). */
public int getHits(int timestamp) {
int totalHits = 0;
// Iterate through all the buckets.
for (int i = 0; i < windowSize; i++) {
// Check if the timestamp in the bucket is within the 300-second window.
// The valid window is (timestamp - 300, timestamp].
if (timestamp - timestamps[i] < windowSize) {
totalHits += hits[i];
}
}
return totalHits;
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
Design Hit Counter in C++
class HitCounter {
private:
// We use a window size of 300 for 5 minutes.
static const int window_size = 300;
// timestamps[i] stores the timestamp of a hit that maps to bucket i.
std::vector<int> timestamps;
// hits[i] stores the number of hits for the timestamp in timestamps[i].
std::vector<int> hits;
public:
/** Initialize your data structure here. */
HitCounter() {
timestamps.resize(window_size, 0);
hits.resize(window_size, 0);
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds). */
void hit(int timestamp) {
// Map the timestamp to a bucket index using modulo.
// We use (timestamp - 1) because timestamps are 1-based.
int index = (timestamp - 1) % window_size;
// If the timestamp in the bucket is the same as the current timestamp,
// it means we have another hit in the same second.
if (timestamps[index] == timestamp) {
hits[index]++;
} else {
// Otherwise, this bucket is either empty or holds an old timestamp.
// We reset it with the new timestamp and count 1.
timestamps[index] = timestamp;
hits[index] = 1;
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds). */
int getHits(int timestamp) {
int total_hits = 0;
// Iterate through all buckets.
for (int i = 0; i < window_size; ++i) {
// Check if the hit recorded in the bucket is within the last 300 seconds.
// The window is (timestamp - 300, timestamp].
if (timestamp - timestamps[i] < window_size) {
total_hits += hits[i];
}
}
return total_hits;
}
};
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter* obj = new HitCounter();
* obj->hit(timestamp);
* int param_2 = obj->getHits(timestamp);
*/
Design Hit Counter in TypeScript
class HitCounter {
private windowSize: number;
private timestamps: number[];
private hits: number[];
constructor() {
this.windowSize = 300; // 5 minutes in seconds
this.timestamps = new Array(this.windowSize).fill(0);
this.hits = new Array(this.windowSize).fill(0);
}
hit(timestamp: number): void {
// Map the timestamp to an index in our circular arrays.
// We use (timestamp - 1) as timestamps are 1-based.
const index = (timestamp - 1) % this.windowSize;
// If the timestamp at this index matches the current timestamp,
// it's a hit within the same second.
if (this.timestamps[index] === timestamp) {
this.hits[index]++;
} else {
// If it's a different timestamp, it means this bucket is either
// new or being recycled for a new second. Reset the bucket.
this.timestamps[index] = timestamp;
this.hits[index] = 1;
}
}
getHits(timestamp: number): number {
let totalHits = 0;
// Iterate through all the buckets.
for (let i = 0; i < this.windowSize; i++) {
// Check if the timestamp in the bucket is within the 300-second window.
// The valid window is (timestamp - 300, timestamp].
if (timestamp - this.timestamps[i] < this.windowSize) {
totalHits += this.hits[i];
}
}
return totalHits;
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* var obj = new HitCounter()
* obj.hit(timestamp)
* var param_2 = obj.getHits(timestamp)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.