Number of Recent Calls

Task example: Number of Recent Calls

Implement RecentCounter. Each ping(t) records a request at time t and returns how many recorded requests fall inside [t - 3000, t], including both endpoints. Timestamps are strictly increasing integer milliseconds.

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

At t = 3001, time 1 is exactly 3000 milliseconds old and still counts. At t = 3002, time 1 is outside the window, leaving three recent requests.

Example 2
Input
ping(1), ping(3002)
Output
[1, 1]

After a gap longer than 3000 milliseconds, only the new request remains in this example.

Each timestamp is between 1 and 1000000000. Calls arrive in strictly increasing order. The examples show the returned value of each ping, starting with a new counter.

LeetCode 933 ↗
01 / Baseline: scan history

Scan history: video explanation

ping(1), ping(100), ping(3001), ping(3002)
[1, 2, 3, 3]

Prefer reading? Follow the steps below.

  1. Append the new timestamp to history. Set count to zero for this ping.
  2. Visit every stored timestamp. Count it when time is at least t - 3000. Equality counts: the lower boundary belongs to the window.
  3. Return the count. Because calls arrive in increasing order, no stored timestamp is greater than t. Expired requests remain in history and are checked again on later calls.

Time complexity · O(n) per ping

After n calls, a ping scans n timestamps. Across n calls, these repeated scans take O(n²) total time.

Space complexity · O(n)

Every request remains stored, so the history uses O(n) space after n calls.

PYTHONLive code trace
02 / Efficient: keep a queue

Queue: video explanation

ping(1), ping(100), ping(3001), ping(3002)
[1, 2, 3, 3]

Prefer reading? Follow the steps below.

  1. Append t to the back of a deque. Its front holds the oldest remaining timestamp.
  2. While the front is less than t - 3000, remove it with popleft(). Stop when the front reaches the lower bound or is newer. Use <, not <=.
  3. Return the queue length. All remaining timestamps are inside the inclusive window. The newest timestamp always remains, so this loop never empties the queue.

Since time only moves forward, an expired request can never matter again. Removing it once avoids scanning the full history on every ping.

Time complexity · O(1) amortized per ping

Each timestamp enters once and leaves at most once: O(n) total work for n calls. A single ping may remove k expired entries and take O(k) time.

Space complexity · O(k) active requests

Only the active window is retained. O(n) is a general upper bound. Here, distinct integer timestamps and a fixed 3000 ms window limit the queue to 3001 entries after a ping, so it is also constant space under these fixed constraints.

PYTHONLive code trace

Number of Recent Calls · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.