Problem
You have a RecentCounter
class which counts the number of recent requests within a certain time frame.
Implement the RecentCounter
class:
RecentCounter()
Initializes the counter with zero recent requests.int ping(int t)
Adds a new request at timet
, wheret
represents some time in milliseconds, and returns the number of requests that has happened in the past3000
milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range[t - 3000, t]
.
It is guaranteed that every call to ping
uses a strictly larger value of
t
than the previous call.
Examples
Example 1
|
|
Constraints
1 <= t <= 10^9
- Each test case will call
ping
with strictly increasing values oft
. - At most
104
calls will be made toping
.
Solution
Method 1 – Sliding Window with Queue
Intuition
We need to count the number of requests in the last 3000 milliseconds. Since pings arrive in increasing order, we can use a queue to store the timestamps and remove old ones from the front as new pings arrive.
Approach
- Use a queue to store the timestamps of pings.
- For each new ping at time t, add t to the queue.
- Remove timestamps from the front of the queue if they are less than t-3000.
- The size of the queue is the answer.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
amortized per ping, since each request is added and removed at most once. - 🧺 Space complexity:
O(n)
, wheren
is the number of pings in the last 3000 ms.