Algo-Sim › Low-Level Design
Design Hit Counter
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
Count hits in the last 5 minutes: a queue of timestamps, dropping expired ones from the front. Each hit is pushed and popped once, so O(1) amortized.
Problem
Design a hit counter. hit(timestamp) records a hit at that second, and getHits(timestamp) returns how many hits happened in the past 300 seconds, that is in (timestamp − 300, timestamp]. Calls arrive in non-decreasing time order.
Constraints
- 1 ≤ timestamp ≤ 2 · 10⁹, non-decreasing
- Up to 300 calls
- hit O(1); getHits O(1) amortized (each hit is removed at most once)
Edge cases to test
- Many hits at the same second
- A query long after the last hit:
0 - Hits exactly 300 seconds ago (expired)
Follow-up questions
- What if hits arrive at huge rates?
- Use 300 buckets of (timestamp, count) indexed by
t % 300: O(1) memory and O(300) per query. - How do you scale it across machines?
- Count locally per bucket and merge the buckets from every server when reading.
Solution
Java
class HitCounter {
private final Deque<Integer> hits = new ArrayDeque<>(); // timestamps, oldest first
public void hit(int timestamp) {
hits.addLast(timestamp);
}
public int getHits(int timestamp) {
while (!hits.isEmpty() && hits.peekFirst() <= timestamp - 300)
hits.pollFirst();
return hits.size();
}
}Python
from collections import deque
class HitCounter:
def __init__(self):
self.hits = deque() # timestamps, oldest first
def hit(self, timestamp):
self.hits.append(timestamp)
def getHits(self, timestamp):
while self.hits and self.hits[0] <= timestamp - 300:
self.hits.popleft()
return len(self.hits)C++
#include <bits/stdc++.h>
using namespace std;
class HitCounter {
public:
deque<int> hits = {}; // timestamps, oldest first
void hit(int timestamp) {
hits.push_back(timestamp);
}
int getHits(int timestamp) {
while (!hits.empty() && hits.front() <= timestamp - 300)
hits.pop_front();
return int(hits.size());
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)