Number of Recent Calls

Count how many requests arrived in the last 3000 milliseconds, with a queue that forgets old ones.

Write a class with one method, ping(t). Each call records a request at time t, in milliseconds, and returns how many requests happened in the range [t - 3000, t], both ends included. The count includes the request just recorded. Each call's t is larger than the t of the call before.

Example 1
Input: ping(1), ping(100), ping(3001), ping(3002)
Output: 1, 2, 3, 3
Explanation: for t = 3002 the range is [2, 3002], which no longer includes the ping at 1.
Solution

The Idea

A web server that turns away users who send too many requests has to answer one question each time a request comes in: how many requests arrived recently? In this problem, recently means the last 3000 milliseconds, which is three seconds, counting the request that just arrived.

Follow Example 1. The first ping, at time 1, is alone, so it returns 1. The ping at 100 returns 2. At 3001 the range is [1, 3001], and the ping at 1 sits exactly on its left edge, so it still counts and the answer is 3. At 3002 the range becomes [2, 3002], the ping at 1 falls out, and the answer stays 3.

So every new ping moves the range to the right, and old pings drop off its left end. A range like this, which slides along with each new ping, is called a sliding window. Do we have to look at every ping ever stored to count the ones inside it? No, because the times only grow. The ping at 1 is outside the window of ping(3002), and every later window starts even further right, so that ping can be forgotten for good.

The picture shows the moment of ping(3002).

Pings at 1, 100, 3001 and 3002 on a time line. The window for ping(3002) is [2, 3002]. In the queue below, 1 is dropped from the front, 3002 is added at the back, and 3 times are left, so ping(3002) returns 3.

The orange band on the time line is the window for ping(3002), [2, 3002], and the grey dot for ping(1) lies left of it. Below the time line, the stored times sit in a row with the oldest on the left, at the front. The new time 3002 is added at the back, and 1, grey and crossed out, is dropped from the front. The teal bracket covers the 3 times left, which is the answer.

A row of ping times that grows at the back and shrinks from the front is a queue. Because the times arrive in order, the pings that fall out of the window are always the ones at the front of the queue, so the cleanup never has to look anywhere else.

Solution Approach

Three choices remain: where the ping times are kept, which times to drop on each call, and how to count the ones left.

Keeping the ping times

Where do the times go? The simple way is a list of every ping ever made, counted from the start on each call. That gives the right answers, but after a million pings each call checks a million times, even though at most 3001 different whole-millisecond times fit inside one window.

The queue from the picture keeps only the pings that can still count. Here it is an ArrayDeque<Integer> named window: addLast puts a new time at the back, peekFirst reads the oldest time without removing it, and pollFirst removes that oldest time.

Which times to drop

Which comparison decides that a time is too old? The range [t - 3000, t] includes its left edge, so a time equal to t - 3000 stays. Only times smaller than t - 3000 go, so a while loop removes times from the front as long as the oldest one is < t - 3000. Pings at 1 and 3001 are exactly 3000 apart, and the second call must return 2.

Can that loop empty the queue and then read from nothing? No. The time just added is t itself, which is never smaller than t - 3000, so the loop stops at it at the latest, and peekFirst() never sees an empty queue.

Counting the pings left

Once the loop stops, every time in the queue lies inside the window, and nothing outside it is stored. So the answer is simply window.size(), with no counting loop at all.

Java Solution

The class has one field and one method, and four pieces of them do the work:

  • window: the queue of ping times, oldest at the front, holding only the pings inside the latest window.
  • window.addLast(t): the first line of ping, which records the new request at the back.
  • The while loop in ping: drops times smaller than t - 3000 from the front.
  • window.size(): the answer, the number of pings still in the window.

The main method runs Example 1 and prints the queue left behind, then tries three more cases, each on a new counter: two pings exactly 3000 apart, a long gap after three quick pings, and a ping every millisecond from 1 to 10000.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class NumberOfRecentCalls {

    private final Deque<Integer> window = new ArrayDeque<>();   // ping times, oldest first

    public int ping(int t) {
        window.addLast(t);
        while (window.peekFirst() < t - 3000) {
            window.pollFirst();       // too old for this ping, and for every later one
        }
        return window.size();
    }

    public static void main(String[] args) {
        NumberOfRecentCalls counter = new NumberOfRecentCalls();
        System.out.println("Example 1: " + counter.ping(1) + ", " + counter.ping(100) + ", "
                + counter.ping(3001) + ", " + counter.ping(3002) + "  queue " + counter.window);

        NumberOfRecentCalls edge = new NumberOfRecentCalls();
        System.out.println("Exactly 3000 apart: " + edge.ping(1) + ", " + edge.ping(3001));

        NumberOfRecentCalls gap = new NumberOfRecentCalls();
        gap.ping(1);
        gap.ping(2);
        gap.ping(3);
        System.out.println("Long gap: ping(5000) returns " + gap.ping(5000)
                + "  queue " + gap.window);

        NumberOfRecentCalls busy = new NumberOfRecentCalls();
        int last = 0;
        for (int t = 1; t <= 10000; t++) {
            last = busy.ping(t);
        }
        System.out.println("A ping every ms from 1 to 10000: last call returns " + last);
    }
}

Running it prints:

Output
Example 1: 1, 2, 3, 3  queue [100, 3001, 3002]
Exactly 3000 apart: 1, 2
Long gap: ping(5000) returns 1  queue [5000]
A ping every ms from 1 to 10000: last call returns 3001

Example 1 gives 1, 2, 3, 3, and the queue left behind is [100, 3001, 3002], the same three boxes as in the picture. On the line Exactly 3000 apart: 1, 2, the ping at 1 sits on the left edge of [1, 3001] and still counts. On the Long gap line, the single call ping(5000) removed all three earlier times, leaving only [5000]. The last line shows a full window: at t = 10000 the range is [7000, 10000], and every one of its 3001 milliseconds has a ping.

The edge case is easy to break. A copy of the class with <= in place of < in the loop condition returns 1, 1 for the pings at 1 and 3001, because it also drops a ping that is exactly 3000 ms old.

Complexity

Each ping time enters the queue once and leaves it at most once, so the work spread over many calls stays small, even when a single call removes several times.

  • Time: O(1) amortised per ping, meaning on average over all calls, because across n pings the while loop can remove at most n times in total. One call can still do more work, as ping(5000) did when it removed three times.
  • Space: O(W), where W is the most pings inside one 3000 ms window, because the queue keeps only those pings. With whole-millisecond times that are all different, W is at most 3001, the count on the last output line.

Sliding windows over arrays are introduced in Sliding Window Basics.