The Design Hit Counter interview question asks you to build a system that counts hits (events) received in the past 5 minutes (300 seconds). You need to implement hit(timestamp) and getHits(timestamp). This Design Hit Counter coding problem is a time-series aggregation task that requires efficiently discarding old data as time moves forward.
Reddit and Apple use this question to test your mastery of Data Stream interview patterns and Queue interview patterns. It evaluates how you handle data that "expires" and whether you can optimize for memory by only storing the necessary window of time. It's a classic systems-design scenario.
There are two main ways to solve this:
Queue. For getHits, peek at the front and remove all timestamps older than currentTime - 300. The size of the queue is the answer.times[] and hits[].
index = timestamp % 300.times[index] matches the timestamp, increment hits[index].times[index] to the new timestamp and set hits[index] to 1.getHits sums the hits[] array for all indices where times[index] is within the window.hit(1), hit(2), hit(3): Hits: [1, 2, 3].getHits(4): . All hits are after -296. Returns 3.hit(301): Hit added at 301.getHits(301): . The hit at timestamp 1 is exactly 300 seconds old? Usually, the interval is (t-300, t]. So hit at 1 is removed.getHits call instead of using a sliding window or a queue.The Circular Array approach is generally preferred because it uses space (300 cells) regardless of how many millions of hits occur. This makes it extremely memory-efficient for high-traffic systems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Moving Average from Data Stream | Easy | Solve | |
| First Unique Number | Medium | Solve | |
| Design Front Middle Back Queue | Medium | Solve | |
| Implement Router | Medium | Solve | |
| Number of Recent Calls | Easy | Solve |