Sponsored
Sponsored
One natural approach to solve this problem is to use a queue data structure. A queue is perfect for this task because it works on a first-in-first-out (FIFO) principle. When a new request arrives, we add it to the queue. We also remove requests from the front of the queue that are older than 3000 milliseconds compared to the current time t
. This allows us to keep only the requests within the last 3000 milliseconds in the queue. The number of such requests is simply the size of the queue after cleaning.
Time Complexity: Amortized O(1) because each request can only be removed once from the queue.
Space Complexity: O(W), where W is the maximum number of recent requests within 3000 milliseconds.
1using System.Collections.Generic;
2
3public class RecentCounter {
4 private Queue<int> queue;
5
6 public RecentCounter() {
7 queue = new Queue<int>();
8 }
9
10 public int Ping(int t) {
11 queue.Enqueue(t);
12 while (queue.Peek() < t - 3000) {
13 queue.Dequeue();
14 }
15 return queue.Count;
16 }
17}
In this C# solution, we use a Queue
to manage the ping requests. We enqueue incoming requests and dequeue any requests that fall outside the relevant window.
An alternative approach to using a queue is to use a double-ended queue (deque). While similar to a queue, a deque allows us to add and remove elements from both ends, but in this problem, we'll only need the standard queue operations.
The logic remains the same: insert new request times to the back of the deque and remove outdated ones from the front. This keeps the deque maintaining only the relevant requests within the [t-3000, t] range.
Time Complexity: Amortized O(1) for each ping
due to efficient pop and push operations.
Space Complexity: O(W), where W is size of the time window.
1#include <deque>
2using namespace std;
3
class RecentCounter {
deque<int> deq;
public:
RecentCounter() {}
int ping(int t) {
deq.push_back(t);
while (!deq.empty() && deq.front() < t - 3000) {
deq.pop_front();
}
return deq.size();
}
};
This C++ implementation uses a deque
from the standard library to manage timestamps. Similar to a queue, we check and remove outdated times once each new ping
is added.