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.ping(int t) -> int
Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request).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:
Input: [1, 100, 3001, 3002]
, Output:[1, 2, 3, 3]
Input: [1, 3001, 6001]
, Output: [1, 2, 2]
popleft()
.
For queues in python we use the deque()
class from collections.
from collections import deque
class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t: int) -> int:
self.q.append(t)
while t - self.q[0] > 3000:
self.q.popleft()
return len(self.q)
The time complexity of this solution is \(O(1)\): at max, there will be 3000 elements in the queue since it is gauranteed that each timestamp will be greater than the previous. The space complexiy is also constant, for the same reason.
If we wanted to run it on an example:
## [1, 2, 3, 3]