You have a RecentCounter
class which counts the number of recent requests within a 3000-millisecond time frame.
Implementation Details
RecentCounter()
: Initializes the counter with zero recent requests.
ping(t)
: Adds a new request at time t
(milliseconds) and returns the number of requests that have happened in the past 3000 milliseconds, i.e., within [t - 3000, t]
.
Constraints
1 <= t <= 10^9
- Calls to
ping
are strictly increasing in t
.
- At most
10^4
calls will be made to ping
.
Example
Input:
Approach
We use a queue (implemented with an array) to store the timestamps of recent requests. When a new request is added:
- Append the timestamp to the queue.
- Remove timestamps from the front of the queue that are older than
t - 3000
.
Steps
- Initialize an empty queue to store timestamps.
- For each
ping(t)
:
- Add the timestamp
t
to the queue.
- Remove timestamps from the front of the queue that are less than
t - 3000
.
- Return the size of the queue as the count of recent requests.
Time & Space Complexity
- Time Complexity:
- Each call to
ping
has a worst-case complexity of O(n), where n
is the number of elements in the queue. This occurs if all timestamps in the queue are outside the valid range.
- Amortized complexity is O(1) because each element is added and removed from the queue exactly once.
- Space Complexity: O(n), where
n
is the number of timestamps in the queue.
Code Snippet