Number of Recent Calls
Problem
Design a counter that tracks how many requests arrived in the last 3000 milliseconds.
Implement RecentCounter() and int ping(int t), where t is a strictly increasing timestamp. Each ping records a request at time t and returns the number of requests whose timestamp is in the inclusive range [t - 3000, t].
Constraints
- 1 ≤ t ≤ 10⁹
- each call uses a strictly larger t
- at most 10⁴ calls
Approach — Sliding Window
This is a Sliding Window problem. The idea: keep a moving window over the sequence, expanding and shrinking it while tracking the answer in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
from collections import deque
class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t):
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
Java
import java.util.ArrayDeque;
import java.util.Deque;
class RecentCounter {
private Deque<Integer> queue;
public RecentCounter() {
queue = new ArrayDeque<>();
}
public int ping(int t) {
queue.addLast(t);
// Drop everything older than the 3000ms window.
while (queue.peekFirst() < t - 3000) {
queue.pollFirst();
}
return queue.size();
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Number of Recent Calls interactively → ← All solutions