933. Number of Recent Calls
On LeetCode ->Problem¶
Implement a counter whose ping(t) records a request and returns the number of requests in the inclusive interval \([t - 3000, t]\). Timestamps are strictly increasing integers.
Key trick¶
Use a queue: increasing timestamps mean expired requests are always at the front and can be permanently removed.
Trap¶
- Remove timestamps strictly less than
t - 3000, not equal to it. - Use
deque.popleft(), not the linear-timelist.pop(0). - A single call can remove many requests; constant time is amortized.
Why is it interesting?¶
It turns a streaming sliding-window problem into a queue where each request is added and removed at most once.
Python solution¶
from collections import deque
class RecentCounter:
def __init__(self):
self.requests = deque()
def ping(self, t: int) -> int:
self.requests.append(t)
while self.requests[0] < t - 3000:
self.requests.popleft()
return len(self.requests)
Time: \(O(1)\) amortized per call, \(O(n)\) total for \(n\) calls.
Space: \(O(\min(n, 3001))\), since an inclusive 3000-millisecond window contains at most 3001 distinct integer timestamps.
Comment on my solution¶
Your algorithm and boundary condition are correct, with the same complexity as above.
- Add
from collections import dequeif it is not imported elsewhere. self.cntis redundant:len(self.requests)is constant-time and avoids maintaining duplicate state.- The nonempty check is safe but unnecessary because the newly appended timestamp cannot expire.