Number of Recent Calls
Number of Recent Calls
QueueDesign
Problem Statement
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 timet
, wheret
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.
Example
Example 1:
Operation Sequence:
ping(1)returns: 1
ping(100)returns: 2
ping(3001)returns: 3
ping(3002)returns: 3
Solution
A queue is the perfect data structure for this problem because we are interested in a sliding window of time. As new pings arrive, we can efficiently remove old pings that fall outside the 3000ms window from the front of the queue.
Algorithm Steps
- Initialize a queue to store the timestamps of the pings.
- When a new ping arrives at time `t`, add it to the queue.
- Remove all timestamps from the front of the queue that are older than `t - 3000`.
- The size of the queue is the number of recent calls.
Current Ping: N/A
Queue:
Start with an empty queue.
Number of Recent Calls Solution