933. Number of Recent Calls
Problem
Design RecentCounter, whose ping(t) records a request at time t (in ms, strictly increasing) and returns the number of requests in the window [t − 3000, t].
Example: pings at 1, 100, 3001, 3002 → 1, 2, 3, 3
Pings arrive in increasing time order, so a queue works: push t, pop from the front while it's older than t − 3000; the queue length is the answer.
Complexity: amortized O(1) per ping.
class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t: int) -> int:
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
rc = RecentCounter()
assert [rc.ping(t) for t in (1, 100, 3001, 3002)] == [1, 2, 3, 3]
rc2 = RecentCounter()
assert [rc2.ping(t) for t in (1, 3001, 3002, 6003)] == [1, 2, 2, 1]
class RecentCounter {
private final Deque<Integer> q = new ArrayDeque<>();
public int ping(int t) {
q.add(t);
while (q.peek() < t - 3000) q.poll();
return q.size();
}
}
type RecentCounter struct {
q []int // ping times within the last 3000 ms
}
func Constructor() RecentCounter {
return RecentCounter{}
}
func (this *RecentCounter) Ping(t int) int {
this.q = append(this.q, t)
for this.q[0] < t-3000 {
this.q = this.q[1:]
}
return len(this.q)
}