Number of Recent Calls - Problem
You're building a real-time request monitoring system that tracks recent API calls within a sliding time window. Your task is to implement a RecentCounter class that efficiently counts requests within the past 3000 milliseconds.
Class Requirements:
RecentCounter()- Initialize the counter with zero recent requestsint ping(int t)- Add a new request at timetand return the count of all requests in the range[t-3000, t](inclusive)
Key constraint: Each call to ping uses a strictly increasing value of t, making this a data stream problem where we process requests in chronological order.
Example: If requests come at times [1, 100, 3001, 3002], when we ping at time 3002, we only count requests from time 2 onwards, which gives us [3001, 3002] = 2 requests.
Input & Output
example_1.py โ Basic Usage
$
Input:
counter = RecentCounter()
counter.ping(1)
counter.ping(100)
counter.ping(3001)
counter.ping(3002)
โบ
Output:
[1, 2, 3, 3]
๐ก Note:
At t=1: count [1] = 1. At t=100: count [1,100] = 2. At t=3001: count [1,100,3001] = 3. At t=3002: count [3001,3002] = 3 (requests at 1,100 are older than 3000ms)
example_2.py โ Large Time Gap
$
Input:
counter = RecentCounter()
counter.ping(1)
counter.ping(10000)
counter.ping(10001)
โบ
Output:
[1, 1, 2]
๐ก Note:
At t=1: count [1] = 1. At t=10000: count [10000] = 1 (t=1 expired). At t=10001: count [10000,10001] = 2
example_3.py โ Exact Boundary
$
Input:
counter = RecentCounter()
counter.ping(1)
counter.ping(3001)
counter.ping(3002)
โบ
Output:
[1, 2, 2]
๐ก Note:
At t=3001: requests in [1,3001] both valid. At t=3002: window is [2,3002], so t=1 just expires, leaving [3001,3002]
Constraints
- 1 โค t โค 109
- Each call to ping uses a strictly larger value of t than the previous call
- At most 104 calls will be made to ping
- Important: The time window is always [t-3000, t] inclusive
Visualization
Tap to expand
Understanding the Visualization
1
Person Enters
A new visitor enters the building at time t
2
Clean Old Records
System automatically removes entry records older than 50 minutes
3
Add New Record
New entry is added to the active monitoring list
4
Count Active Visitors
System reports how many people entered in the last 50 minutes
Key Takeaway
๐ฏ Key Insight: Using a queue for chronologically ordered data allows O(1) amortized operations - each request is processed exactly once when added and once when removed.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code