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
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output
[null, 1, 2, 3, 3]
Explanation
ping with strictly increasing values of t.ping.The problem requires us to count the number of calls within a sliding window of 3000 milliseconds. One straightforward approach is to maintain a list of timestamps and iterate over them to count how many fall within this range each time a new call is added.
ping, calculate the time window [t - 3000, t].O(n) where n is the number of timestamps stored. This is because we may need to iterate over the list to count.O(n) since we need to store all the timestamps.Instead of iterating over all past calls, we can use a queue to efficiently add new timestamps and remove old ones that fall out of the sliding window, maintaining only the relevant timestamps within the queue.
ping, add the current timestamp to the queue.[t - 3000].ping operation is O(1) on average since we are performing operations that affect only the current and the oldest timestamps.O(n) where n is the number of timestamps in the last 3000 milliseconds.