AAlgoLoopSpaced repetition for LeetCode
EASYStack / QueueLeetCode ↗

Number of Recent Calls

The key idea

Timestamps arrive in strictly increasing order, so the only requests that can fall out of the window [t-3000, t] are the OLDEST ones. A FIFO queue lets you append each new ping at the back and pop stale timestamps from the front; the answer is just the queue's size after pruning.

Problem

Design a RecentCounter class that counts the number of recent requests within a fixed time window. The counter starts with zero requests. Each call to ping(t) records a new request at time t (in milliseconds) and returns how many requests have occurred in the inclusive range from t - 3000 to t, counting the new request itself. Every call to ping is guaranteed to use a strictly larger value of t than the previous call.

Constraints

Examples

Input: ["RecentCounter","ping","ping","ping","ping"] [[],[1],[100],[3001],[3002]] Output: [null,1,2,3,3]

Complexity

Time: O(1) Space: O(W)

See the full solution

410310
Step-by-step visualization
Start free →

More Stack / Queue problems