Optimal: queue of timestamps
Time O(1) amortised per ping Space O(window size)Offer t, then poll from the front while the front is < t − 3000. The queue size is the answer. Each ping is added and removed once.
import java.util.ArrayDeque;
import java.util.Queue;
class RecentCounter {
private final Queue<Integer> pings = new ArrayDeque<>();
public RecentCounter() {}
public int ping(int t) {
pings.offer(t);
while (pings.peek() < t - 3000) pings.poll();
return pings.size();
}
}Verdict: This is how simple sliding-window rate limiters work.