Number of Recent Calls (LeetCode 933): Solution and Explanation
Implement RecentCounter, whose ping(t) records a request at time t and returns how many requests fall in the inclusive window [t - 3000, t]. The times strictly increase from call to call.
Intuition
The brute force answer keeps every ping and counts the ones inside the window on each call. That is O(n) per call and gets slow over 10^4 calls.
The key fact is that t only goes up. Once a ping is older than t - 3000, it is older than every later window too, so it can be thrown away for good.
The pings that survive are always the newest ones, a contiguous run at the end of the history. New pings join at the back and stale ones leave from the front, which is exactly what a queue does.
After trimming the front, everything in the queue is inside the window, so the answer is simply the queue length.
Approach: Queue as a sliding window
- Keep a queue of ping times, oldest at the front.
ping(t): pushtto the back.- While the front of the queue is less than
t - 3000, pop it. It can never be inside a window again. - Return the size of the queue.
Step-by-step example
commands = ["RecentCounter","ping","ping","ping","ping"], values = [[],[1],[100],[3001],[3002]]
ping(1): the queue is [1]. The window is [-2999, 1], so nothing is dropped. Return 1.ping(100): the queue is [1, 100] and the window is [-2900, 100]. Return 2.ping(3001): the window is [1, 3001]. The front ping 1 equals the lower bound, and the window is inclusive, so it stays. Return 3.ping(3002): the window is [2, 3002]. The front ping 1 is below 2, so it is dropped. The new front 100 is inside, so the loop stops. Return 2 + 1 = 3.- Output: [null,1,2,3,3].
Code: Python, Java, C++
1from collections import deque
2
3class RecentCounter:
4 def __init__(self):
5 self.q = deque()
6
7 def ping(self, t: int) -> int:
8 self.q.append(t)
9 while self.q[0] < t - 3000:
10 self.q.popleft()
11 return len(self.q)1class RecentCounter {
2 private Queue<Integer> q;
3
4 public RecentCounter() {
5 q = new ArrayDeque<>();
6 }
7
8 public int ping(int t) {
9 q.offer(t);
10 while (q.peek() < t - 3000) {
11 q.poll();
12 }
13 return q.size();
14 }
15}1class RecentCounter {
2 queue<int> q;
3
4public:
5 RecentCounter() {}
6
7 int ping(int t) {
8 q.push(t);
9 while (q.front() < t - 3000) {
10 q.pop();
11 }
12 return q.size();
13 }
14};Time and space complexity
O(1) amortized per ping
Each ping is pushed once and popped at most once, so n calls do O(n) work in total.
O(W)
The queue holds only pings inside one 3000 ms window. Times are distinct integers, so W is at most 3001.
Other approaches
Binary search over all pings (time O(log n) per ping, space O(n))
Keep every ping in a sorted list (appending keeps it sorted) and binary search for the first ping that is at least t - 3000. The answer is the number of pings after that index. It never deletes, so memory grows with every call.
Count every ping on each call (time O(n) per ping, space O(n))
Store all pings and count those in [t - 3000, t] on each call. Simple, but O(n) per call.
Common mistakes
- Using
<=instead of<when trimming. The window is inclusive, so a ping exactly att - 3000must still be counted. - Using a JavaScript array with
shift()as the queue.shiftcopies the array, so a long run turns O(1) pops into O(n). Keep a head index instead. - Checking the front of an empty queue. Pushing
tbefore trimming guarantees the queue is never empty during the loop, becausetitself is always in its own window.
Frequently asked questions
Why does the loop never empty the queue?
t is pushed first, and t is never less than t - 3000. So the loop always stops by the time it reaches the newest ping.
What if the times were not increasing?
Then a dropped ping could belong to a later window, and the queue trick breaks. You would need a sorted structure, such as a balanced tree or a sorted list with binary search, to count the pings in a range.
How is this related to rate limiting?
It is the sliding window log used by rate limiters: keep the timestamps of recent requests, drop the ones that fall out of the window, and compare the remaining count with the limit.