Problem
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
Examples
Example 1:
|
|
Follow up: What if the number of hits per second could be very large? Does your design scale?
Similar Problem
Design hit counter with range queries
Solution
Method 1 - Use Queue
We need to design a system that can efficiently record hits and fetch the number of hits received in the last 5 minutes (300 seconds).
Approach
- Data Structure: Use a queue to maintain the timestamps of hits.
- Record Operation: Add a new hit to the queue with the given timestamp.
- Get Hits Operation: Remove hits from the front of the queue that are older than 300 seconds from the current timestamp. The remaining hits in the queue are within the last 5 minutes.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
hit(timestamp)
:O(1)
as it’s a simple enqueue operation.getHits(timestamp)
:O(n)
wheren
is the number of hits in the queue due to the potential need to remove outdated hits.
- 🧺 Space complexity:
O(n)
wheren
is the number of hits within the last 300 seconds.