Number of Recent Calls

Easy DesignQueueSliding Window

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].

Example 1 Input: ping(1), ping(100), ping(3001), ping(3002) Output: 1 2 3 3

Constraints

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