Coding Interview PatternsDesign Hit Counter
MediumCustom Data Structures
Design Hit Counter
Explanation & Solution
Description
Design a hit counter that counts the number of hits received in the past 300 seconds.
Implement a function that processes an array of operations and an array of arguments:
"HitCounter"— Initializes the hit counter."hit"— Records a hit at the giventimestamp(in seconds). Multiple hits may have the same timestamp."getHits"— Returns the number of hits in the past 300 seconds fromtimestamp(inclusive oftimestamp - 299totimestamp).
The timestamp values passed to hit and getHits are non-decreasing.
Input:operations = ["HitCounter","hit","hit","hit","getHits","hit","getHits","getHits"], args = [[],[1],[2],[3],[4],[300],[300],[301]]
0
HitCounter
1
hit
2
hit
3
hit
4
getHits
5
hit
6
getHits
7
getHits
Output:[null,null,null,null,3,null,4,3]
0
null
1
null
2
null
3
null
4
3
5
null
6
4
7
3
Explanation: Hits at t=1,2,3. getHits(4) counts hits in [1..4] → 3. Hit at t=300. getHits(300) counts [1..300] → 4. getHits(301) counts [2..301] → 3 (t=1 is now outside the 300s window).
Constraints
1 <= timestamp <= 2 * 10^9- All calls to
hitandgetHitsare made in non-decreasing order oftimestamp - At most
300calls will be made tohitandgetHits
Approach
Custom Data Structures pattern
1. Store Timestamps in Order
- Maintain an array of all hit timestamps
- Since timestamps are non-decreasing, the array is inherently sorted
2. Implement Hit
- Simply append the
timestampto the array - Multiple hits at the same timestamp are stored as separate entries
3. Implement GetHits
- Count how many stored timestamps
tsatisfytimestamp - t < 300 - This means
t > timestamp - 300, i.e., the hit is within the last 300 seconds - Since the array is sorted, scan from the back and break once a timestamp falls outside the window
4. Why Scan from the Back?
- The most recent hits are at the end of the array
- Since timestamps are non-decreasing, once you find a timestamp outside the window, all earlier ones are also outside — no need to continue
Key Insight
- The 300-second window means a hit at timestamp
tcounts for anygetHits(q)whereq - t < 300 - Boundary check:
timestamp - hits[i] < 300(strictly less than 300, not 300)
Time
O(n) per getHits, O(1) per hitSpace
O(n) for storing all hits