Design Hit Counter - Problem
Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).
Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). Several hits may arrive roughly at the same time.
Implement the HitCounter class:
HitCounter()Initializes the object of the hit counter system.void hit(int timestamp)Records a hit that happened at timestamp (in seconds). Several hits may happen at the same timestamp.int getHits(int timestamp)Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).
Input & Output
Example 1 — Basic Hit Counter Usage
$
Input:
operations = ["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"], values = [[], [1], [2], [3], [4], [300], [300], [301]]
›
Output:
[null, null, null, null, 3, null, 4, 3]
💡 Note:
Initialize counter, record hits at times 1,2,3. At time 4, all 3 hits are within 300 seconds. Hit at time 300. At time 300, all 4 hits are recent. At time 301, hit at time 1 is now 300+ seconds old, so only 3 hits remain.
Example 2 — Multiple Hits Same Time
$
Input:
operations = ["HitCounter", "hit", "hit", "getHits"], values = [[], [1], [1], [2]]
›
Output:
[null, null, null, 2]
💡 Note:
Two hits at the same timestamp (time 1). getHits(2) counts both hits since they occurred within the past 300 seconds.
Example 3 — Edge Case Window Boundary
$
Input:
operations = ["HitCounter", "hit", "getHits", "getHits"], values = [[], [1], [300], [301]]
›
Output:
[null, null, 1, 0]
💡 Note:
Hit at time 1. At time 300, the hit is exactly 299 seconds ago (within window). At time 301, the hit is exactly 300 seconds ago (outside window).
Constraints
- 1 ≤ timestamp ≤ 2 * 109
- All the calls are being made to the system in chronological order
- At most 300 calls will be made to hit and getHits
Visualization
Tap to expand
Understanding the Visualization
1
Record Hits
Store timestamps of incoming hits
2
Sliding Window
Maintain only hits within past 300 seconds
3
Count Valid
Return number of recent hits
Key Takeaway
🎯 Key Insight: Use sliding window to automatically expire old data and maintain only recent hits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code