Number of Recent Calls - Problem

You have a RecentCounter class which counts the number of recent requests within a certain time frame.

Implement the RecentCounter class:

  • RecentCounter() Initializes the counter with zero recent requests.
  • int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].

It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

Input & Output

Example 1 — Basic Usage
$ Input: operations = ["RecentCounter", "ping", "ping", "ping", "ping"], values = [null, 1, 100, 3001, 3002]
Output: [null, 1, 2, 3, 3]
💡 Note: RecentCounter() creates counter. ping(1) returns 1 (only request 1). ping(100) returns 2 (requests 1,100). ping(3001) returns 3 (requests 1,100,3001). ping(3002) returns 3 (requests 100,3001,3002 - request 1 expired)
Example 2 — All Requests Expire
$ Input: operations = ["RecentCounter", "ping", "ping"], values = [null, 1, 5000]
Output: [null, 1, 1]
💡 Note: ping(1) returns 1. ping(5000) returns 1 because request at time 1 is outside range [5000-3000, 5000] = [2000, 5000]
Example 3 — Close Timestamps
$ Input: operations = ["RecentCounter", "ping", "ping", "ping"], values = [null, 1000, 2000, 3500]
Output: [null, 1, 2, 3]
💡 Note: All requests stay within 3000ms window: ping(3500) checks range [500, 3500] which includes 1000, 2000, 3500

Constraints

  • 1 ≤ t ≤ 109
  • Each test case will call ping with strictly increasing values of t
  • At most 104 calls will be made to ping

Visualization

Tap to expand
Number of Recent Calls - Sliding Time WindowTimeline:110030013002ping(3002) - Window [2, 3002]:3000ms WindowContains: 100, 3001, 3002✓ valid✓ valid✓ valid❌ expired(1 < 2)Output: 3 (three requests in window)
Understanding the Visualization
1
Input
Sequence of ping operations with timestamps
2
Process
Maintain 3000ms sliding window of requests
3
Output
Count of requests in current window for each ping
Key Takeaway
🎯 Key Insight: Use a queue to efficiently maintain only the requests within the sliding time window, removing expired requests from the front.
Asked in
Google 25 Amazon 20 Microsoft 15
95.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen