Design Hit Counter solution explained
Design Hit Counter asks for a class that records hits at given seconds and answers how many hits happened in the last 300 seconds, with calls arriving in non-decreasing time order. Keep a queue of (second, count) pairs and a running total: add to the back on each hit, and before answering, drop pairs from the front that have fallen out of the window. A fixed array of 300 slots indexed by second modulo 300 is the constant-memory alternative.
By Evin JohnPublished 7 min read
Restating the problem
Build a counter with two methods. The first records one hit at a given time in seconds. The second takes a time t and returns the number of hits recorded in the five minutes ending at t, which means every hit whose time h satisfies t - h < 300. Calls to both methods come in order of time (the time passed in never decreases), and several hits may share the same second.
hit(2); hit(2); hit(150)
count(200) -> 3 hits at 2, 2 and 150 are all within 300 seconds
hit(301)
count(301) -> 4 301 - 2 = 299, so the hits at 2 still count
count(302) -> 2 302 - 2 = 300: the hits at 2 have expired
count(460) -> 1 only the hit at 301 remains
count(700) -> 0Pin down the boundary first. Here a hit exactly 300 seconds old no longer counts; some versions of the question include it. Ask, and write the comparison accordingly.
What it tests
It is a small object-oriented design question with a sliding window inside. Interviewers look at whether you use the ordering rule (it makes a queue enough), whether you notice that storing every hit wastes memory under heavy traffic, and how you discuss the follow-ups: what if there are millions of hits per second, and what if the counter runs on several servers.
Slow but sure: keep every hit
Store each hit's time in a list and count the recent ones on every query. It is obviously correct, which makes it the right reference for testing, but the list never shrinks and every query scans all of it.
class HitCounterSlow:
def __init__(self):
self.hits = []
def hit(self, timestamp):
self.hits.append(timestamp)
def get_hits(self, timestamp):
return sum(1 for h in self.hits if timestamp - h < 300)Queue of seconds with a running total
Since times arrive in order, the oldest hit is always at the front. Store one [second, count] pair per distinct second, so a burst of a thousand hits in one second takes one entry, and keep the total of all counts in the queue. A hit either increases the last pair's count or appends a new pair. A query first removes pairs from the front while they are 300 or more seconds old, subtracting their counts, then returns the total.
from collections import deque
class HitCounter:
WINDOW = 300
def __init__(self):
self.buckets = deque() # [second, count], oldest first
self.total = 0
def _expire(self, now):
while self.buckets and now - self.buckets[0][0] >= self.WINDOW:
self.total -= self.buckets.popleft()[1]
def hit(self, timestamp):
self._expire(timestamp)
if self.buckets and self.buckets[-1][0] == timestamp:
self.buckets[-1][1] += 1
else:
self.buckets.append([timestamp, 1])
self.total += 1
def get_hits(self, timestamp):
self._expire(timestamp)
return self.totalExpiring inside hit as well keeps memory bounded even if nobody queries for a long time. Each pair is added once and removed once, so the cost is amortized O(1) per call, and the queue never holds more than 300 pairs.
Fixed memory: a circular buffer of 300 slots
If memory must be fixed in advance, use two arrays of length 300. Second t maps to slot t mod 300. Each slot remembers which second it currently holds and how many hits that second had. When a hit lands in a slot that holds an older second, reset it. A query adds up the counts of the slots whose second is still inside the window. A slot can only be overwritten by a second at least 300 later, by which point the old second has expired anyway, so no live data is ever lost.
class HitCounter {
constructor(window = 300) {
this.window = window;
this.seconds = new Array(window).fill(-Infinity);
this.counts = new Array(window).fill(0);
}
hit(timestamp) {
const slot = timestamp % this.window;
if (this.seconds[slot] !== timestamp) {
this.seconds[slot] = timestamp;
this.counts[slot] = 0;
}
this.counts[slot]++;
}
getHits(timestamp) {
let total = 0;
for (let slot = 0; slot < this.window; slot++) {
if (timestamp - this.seconds[slot] < this.window) total += this.counts[slot];
}
return total;
}
}Starting every slot at minus infinity makes unused slots fail the window test without a special case. The query always touches all 300 slots, which is constant but larger than the queue's typical cost; the trade is predictable memory and no allocation per call.
Complexity
| Design | hit | count query | Memory |
|---|---|---|---|
| List of every hit | O(1) | O(H) | O(H), never shrinks |
| Queue of every hit | O(1) | Amortized O(1) | O(hits in the window) |
| Queue of (second, count) pairs | Amortized O(1) | Amortized O(1) | O(W) pairs at most |
| Circular buffer | O(1) | O(W) | O(W), fixed |
Inputs that catch bugs
- Many hits in the same second: they must all count, and expire together.
- A query exactly 299, 300 and 301 seconds after a hit: check the boundary you agreed on.
- A long silence, then a query: everything expires and the answer is 0.
- A query before any hit: 0, without touching an empty queue.
- Hits only, no queries, for a long time: memory should stay bounded.
Common mistakes
- Using <= instead of < (or the reverse) at the boundary and not testing exactly 300 seconds.
- Returning the length of the queue after grouping hits by second, which counts seconds instead of hits.
- In the circular buffer, adding to a slot without checking which second it holds, so stale counts leak in.
- Expiring only in the query method and letting the queue grow during a long run of hits.
- Ignoring the ordering rule and reaching for a sorted structure or binary search that is not needed.
Follow-ups to prepare
- Huge bursts: grouping by second (or by a coarser bucket) bounds memory regardless of traffic.
- Concurrent callers: guard the update with a lock, or give each thread its own buckets and sum them when counting.
- Several servers: keep per-server buckets and sum them, or send counts to a shared store; mention that clocks can drift between machines.
- Exact versus approximate: coarser buckets trade a little accuracy at the window edge for less memory.
- Out-of-order times: the queue no longer works as is; buckets indexed by second still do, as long as late hits are within the window.
How to explain it out loud
Fictional example
- Candidate
- Times never go backwards, so hits expire in the same order they arrived. That makes a queue enough: push on hit, pop old ones from the front on query.
- Interviewer
- What if a single second gets a million hits?
- Candidate
- Then I store one pair per second, with a count, and keep a running total. The queue holds at most 300 pairs no matter the traffic.
- Candidate
- If memory has to be fixed up front, I can use 300 slots indexed by the second mod 300. Hits are O(1), queries scan the 300 slots, and a slot is only reused once its old second has expired.
Related problems
Other design questions with a time element include My Calendar I and Design Twitter, and LRU Cache is the classic class-design warm-up. In this batch, Exclusive Time of Functions also processes timestamped events in order, and Longest Absolute File Path keeps a small running structure over a stream of lines.
Getting ready with Natively
Design questions are judged as much on the follow-up discussion as on the code. Natively, on Mac or Windows, can read the class outline from a screenshot during a mock round, suggest the queue and the circular buffer along with the trade-offs between them, and transcribe your answers to the scaling questions so you can tighten them before the real interview. Details are on the AI interview assistant page.
Questions people ask
How do you design a hit counter?
Keep a queue of (second, count) pairs and a running total. On a hit, add to the last pair or append a new one. Before answering a count, remove pairs from the front that are 300 or more seconds old and subtract their counts.
How do you design a hit counter with fixed memory?
Use 300 slots indexed by the second modulo 300, each storing its second and count. Reset a slot when a newer second lands in it, and sum the slots still inside the window when counting.
What is the time complexity of the hit counter?
With the queue of pairs both operations are amortized O(1). With the circular buffer, hits are O(1) and counts are O(300).
How would a hit counter work with very high traffic or many servers?
Group hits by second so memory stays bounded, protect updates with a lock or per-thread buckets, and for several servers keep per-server buckets and sum them, keeping clock drift in mind.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
