Number of Recent Calls
Number of Recent Calls is a easy design data structures problem solved with the queue / circular buffer pattern.
The best approach, optimal (queue as a sliding window), runs in O(1) amortised per call time and O(W), W <= 3001 space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (store everything, count each time) up.
Problem
Build a RecentCounter class that counts how many requests arrived in the last 3000 milliseconds.
RecentCounter()starts with no requests recorded.ping(t)records a new request at timet(in milliseconds) and returns how many requests, including this one, happened in the window[t - 3000, t]. Both ends of the window are included.
Every call to ping uses a strictly larger t than the previous call.
Examples
Example 1
- Input
RecentCounter(), ping(1), ping(100), ping(3001), ping(3002)- Output
1, 2, 3, 3- Why
- ping(1) counts only itself. ping(100) looks at [-2900, 100], which holds 1 and 100. ping(3001) looks at [1, 3001]: the window starts exactly at 1, so all three pings count. ping(3002) looks at [2, 3002], so 1 has dropped out and 100, 3001 and 3002 remain.
Example 2
- Input
RecentCounter(), ping(5), ping(3005), ping(3006), ping(6006), ping(9010)- Output
1, 2, 2, 2, 1- Why
- ping(3005) still sees 5, because the window [5, 3005] includes its left end. ping(3006) looks at [6, 3006], so 5 is gone. ping(6006) keeps only 3006 and itself. ping(9010) looks at [6010, 9010], and every earlier ping is older than that, so it counts only itself.
Constraints
1 <= t <= 10^9- Every call to
pinguses a strictly largertthan the call before it. - At most
10^4calls toping.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (store everything, count each time) | O(n) per call | O(n) |
| Sorted list with binary search | O(log n) per call | O(n) |
| Optimal (queue as a sliding window) | O(1) amortised per call | O(W), W <= 3001 |
1Brute force (store everything, count each time)
O(n) per callThe k-th call scans all k stored pings, so n calls take O(n^2) in total.O(n)Every ping is kept forever, n of them after n calls.Keep every ping ever made in a list. On each call, add t and then walk the whole list, counting the times that are at least t - 3000. Since t is the largest time so far, nothing in the list is above t, so this counts exactly the window.
- Append t to the list.
- Count the stored times with time >= t - 3000.
- Return that count.
class RecentCounter {
private final List<Integer> times = new ArrayList<>();
public RecentCounter() {}
public int ping(int t) {
times.add(t);
int count = 0;
for (int x : times) {
if (x >= t - 3000) count++;
}
return count;
}
}class RecentCounter:
def __init__(self):
self.times = []
def ping(self, t: int) -> int:
self.times.append(t)
count = 0
for x in self.times:
if x >= t - 3000:
count += 1
return countclass RecentCounter {
vector<int> times;
public:
RecentCounter() {}
int ping(int t) {
times.push_back(t);
int count = 0;
for (int x : times) {
if (x >= t - 3000) count++;
}
return count;
}
};class RecentCounter {
constructor() {
this.times = [];
}
ping(t) {
this.times.push(t);
let count = 0;
for (const x of this.times) {
if (x >= t - 3000) count++;
}
return count;
}
}2Sorted list with binary search
O(log n) per callOne append (amortised O(1)) and one binary search over at most n stored times.O(n)All pings are still kept, even the ones that can never be counted again.The pings arrive in increasing order, so the list of all pings is already sorted. The pings inside the window form a suffix of that list. Binary search for the first time that is at least t - 3000; everything from there to the end is in the window, so the answer is the list size minus that index.
- Append t; the list stays sorted because t is larger than every earlier time.
- Binary search for the first index whose time is >= t - 3000. It exists, because t itself qualifies.
- Return size - index.
class RecentCounter {
private final List<Integer> times = new ArrayList<>();
public RecentCounter() {}
public int ping(int t) {
times.add(t);
int lo = 0, hi = times.size() - 1;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (times.get(mid) < t - 3000) lo = mid + 1;
else hi = mid;
}
return times.size() - lo;
}
}class RecentCounter:
def __init__(self):
self.times = []
def ping(self, t: int) -> int:
self.times.append(t)
lo, hi = 0, len(self.times) - 1
while lo < hi:
mid = (lo + hi) // 2
if self.times[mid] < t - 3000:
lo = mid + 1
else:
hi = mid
return len(self.times) - loclass RecentCounter {
vector<int> times;
public:
RecentCounter() {}
int ping(int t) {
times.push_back(t);
int lo = 0, hi = times.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (times[mid] < t - 3000) lo = mid + 1;
else hi = mid;
}
return times.size() - lo;
}
};class RecentCounter {
constructor() {
this.times = [];
}
ping(t) {
this.times.push(t);
let lo = 0, hi = this.times.length - 1;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.times[mid] < t - 3000) lo = mid + 1;
else hi = mid;
}
return this.times.length - lo;
}
}3Optimal (queue as a sliding window)
O(1) amortised per callEach ping is added once and removed at most once, so n calls do at most 2n queue operations in total.O(W), W <= 3001Only pings inside the current window stay. Times are distinct integers, so at most 3001 of them fit in a window of width 3000.Once a ping is older than t - 3000, it is older than the window of every later call too, because times only grow. So it can be thrown away for good. New pings join at the back and old ones leave from the front: that is a queue. After adding t and removing every front element below t - 3000, the queue holds exactly the window, and its size is the answer.
- Add t to the back of the queue.
- While the front of the queue is < t - 3000, remove it.
- Return the size of the queue.
class RecentCounter {
private final Deque<Integer> queue = new ArrayDeque<>();
public RecentCounter() {}
public int ping(int t) {
queue.offer(t);
while (queue.peek() < t - 3000) queue.poll();
return queue.size();
}
}class RecentCounter:
def __init__(self):
self.queue = deque()
def ping(self, t: int) -> int:
self.queue.append(t)
while self.queue[0] < t - 3000:
self.queue.popleft()
return len(self.queue)class RecentCounter {
queue<int> q;
public:
RecentCounter() {}
int ping(int t) {
q.push(t);
while (q.front() < t - 3000) q.pop();
return q.size();
}
};class RecentCounter {
constructor() {
this.queue = [];
this.head = 0; // index of the front; the slots before it are removed
}
ping(t) {
this.queue.push(t);
while (this.queue[this.head] < t - 3000) this.head++;
return this.queue.length - this.head;
}
}Edge cases to test
- The very first ping always returns 1, since it counts itself
- A ping exactly 3000 ms older than t is still inside the window (both ends are inclusive)
- A ping 3001 ms older than t is outside the window
- A long silence: the next ping drops every stored ping and returns 1
- Many pings packed close together: the window can hold up to 3001 of them
- t below 3000: the window's left end is negative, which is fine because every ping time is positive
Hints
Hint 1
Because times only go up, a ping that has fallen out of the window for one call will be out of the window for every later call too.
Hint 2
So old pings can be thrown away for good. Which end of your collection do they leave from?
Hint 3
Keep the pings in a queue. On each call add t at the back, remove from the front while the front is older than t - 3000, and return the queue's size.
FAQ
What is the best time complexity for Number of Recent Calls?
Optimal (queue as a sliding window) runs in O(1) amortised per call time and O(W), W <= 3001 extra space. Each ping is added once and removed at most once, so n calls do at most 2n queue operations in total.
Which pattern does Number of Recent Calls use?
It is a design data structures problem that uses the queue / circular buffer pattern. Other problems with the same pattern: Design Hit Counter, Design Circular Queue, First Unique Number.
Is there a brute force solution for Number of Recent Calls?
Yes. Brute force (store everything, count each time) takes O(n) per call time and O(n) space. Keep every ping ever made in a list.
Which edge cases should I test for Number of Recent Calls?
The very first ping always returns 1, since it counts itself; A ping exactly 3000 ms older than t is still inside the window (both ends are inclusive); A ping 3001 ms older than t is outside the window; A long silence: the next ping drops every stored ping and returns 1; Many pings packed close together: the window can hold up to 3001 of them; t below 3000: the window's left end is negative, which is fine because every ping time is positive.