Problem Description
Design a RecentCounter class that counts the number of recent requests (pings) that occurred within a fixed time window of the last 3000 milliseconds. Every time a new ping is made with time t, the class should return the count of all pings that happened in the inclusive time range [t - 3000, t].
Key Insights
- Use a queue (or deque) to store the timestamps of the recent pings.
- Since the ping times are guaranteed to be strictly increasing, the oldest time is always at the front of the queue.
- For each new ping, remove elements from the front of the queue that fall outside the desired time window.
- The remaining elements in the queue represent the pings in the time range [t - 3000, t].
Space and Time Complexity
Time Complexity: O(1) amortized per ping, since each timestamp is added and removed at most once. Space Complexity: O(n), where n is the number of pings stored (at most the number of pings within any 3000 ms window).
Solution
The solution uses a queue data structure to efficiently track and manage the timestamps of the ping requests. When a ping is made:
- Add the new timestamp to the queue.
- Remove all timestamps from the front of the queue that are less than t - 3000.
- The size of the queue then gives the count of recent pings.
This approach leverages the fact that the incoming timestamps are strictly increasing. The removal process ensures that no outdated ping remains in the queue, keeping the data structure clean and efficient.