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
, where t
represents some time in milliseconds, and returns the number of requests that have happened in the past 3000 milliseconds (including the new request).It is guaranteed that every call to ping
uses a strictly larger value of t
than before.
t
be negative?
t
will always be non-negative.t
?
ping
will use increasing values of t
?
To handle the pings efficiently:
ping
is received:
t
.Let’s implement this strategy in Java.
import java.util.LinkedList;
import java.util.Queue;
class RecentCounter {
private Queue<Integer> queue;
public RecentCounter() {
this.queue = new LinkedList<>();
}
public int ping(int t) {
this.queue.offer(t);
while (this.queue.peek() < t - 3000) {
this.queue.poll();
}
return this.queue.size();
}
}
// Example usage
public class Main {
public static void main(String[] args) {
RecentCounter recentCounter = new RecentCounter();
System.out.println(recentCounter.ping(1)); // returns 1
System.out.println(recentCounter.ping(100)); // returns 2
System.out.println(recentCounter.ping(3001)); // returns 3
System.out.println(recentCounter.ping(3002)); // returns 3
}
}
ping
operation involves adding one element to the queue and potentially removing all elements less than t-3000
.n
elements in the queue, all of them might be dequeued when a new ping
arrives, but since each element is added and removed exactly once, the average time complexity per operation is effectively O(1)
.ping
function is O(1)
.This ensures efficient handling of pings within the required time window.
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?