Leetcode 933. Number of Recent Calls
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 no requests.int ping(int t)
Adds a new request at time t
(in milliseconds), where t
represents some time in the past. Returns the number of requests that have been made from t - 3000
to t
(inclusive).It is guaranteed that every call to ping
uses a strictly larger value of t
than the previous call.
t
is a non-negative integer?
t
is guaranteed to be a non-negative integer and always strictly increasing with each call to ping
.t
?
t
can go up to 10^9
, but each call to ping
will have a strictly increasing value of t
.The solution revolves around maintaining a list of request times and efficiently counting how many of them fall within the last 3000 milliseconds of a given request time. Here’s a step-by-step approach:
ping(t)
, add t
to the queue.t - 3000
.The use of a queue ensures that we can efficiently add new request times and remove old ones, keeping the operations approximately O(1) for each call of ping
.
#include <queue>
class RecentCounter {
public:
RecentCounter() {
}
int ping(int t) {
// Add the new request timestamp `t`
q.push(t);
// Remove all requests that are older than `t - 3000`
while (!q.empty() && q.front() < t - 3000) {
q.pop();
}
// The size of the queue is the number of recent requests
return q.size();
}
private:
std::queue<int> q; // Queue to store the timestamps of the requests
};
RecentCounter
constructor): O(1)ping
operation is O(1)
on average.This approach ensures efficient management of the list of requests and handles the problem constraints effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?