Number of Recent Calls

Easy Design Data Structures Queue / Circular Buffer

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 time t (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 ping uses a strictly larger t than the call before it.
  • At most 10^4 calls to ping.

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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (store everything, count each time)O(n) per callO(n)
Sorted list with binary searchO(log n) per callO(n)
Optimal (queue as a sliding window)O(1) amortised per callO(W), W <= 3001

1Brute force (store everything, count each time)

TimeO(n) per callThe k-th call scans all k stored pings, so n calls take O(n^2) in total.
SpaceO(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.

  1. Append t to the list.
  2. Count the stored times with time >= t - 3000.
  3. 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;
    }
}

3Optimal (queue as a sliding window)

TimeO(1) amortised per callEach ping is added once and removed at most once, so n calls do at most 2n queue operations in total.
SpaceO(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.

  1. Add t to the back of the queue.
  2. While the front of the queue is < t - 3000, remove it.
  3. 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();
    }
}

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.