Number of Recent Calls
Problem (restated)
ping(t) records a call at time t (ms). Return how many calls occurred in [t-3000, t].
Intuition
Queue of timestamps; enqueue t, dequeue anything before t-3000, return size.
Approaches
Sliding queue window
UnverifiedIdea. monotonic increasing t guarantees front-only eviction.
Walkthrough. ping(1)→1, ping(100)→2, ping(3001)→3, ping(3002)→3.
Trade-offs. Deque of events is the queue-deque rolling window pattern.
export class RecentCounter {
private q: number[] = [];
private head = 0;
ping(t: number): number {
this.q.push(t);
while (this.head < this.q.length && this.q[this.head]! < t - 3000) this.head++;
// Reclaim the consumed prefix so a long-running stream stays bounded.
if (this.head > 0 && this.head * 2 >= this.q.length) {
this.q = this.q.slice(this.head);
this.head = 0;
}
return this.q.length - this.head;
}
}
export class RecentCounter {
private q: number[] = [];
private head = 0;
ping(t: number): number {
this.q.push(t);
while (this.head < this.q.length && this.q[this.head]! < t - 3000) this.head++;
// Reclaim the consumed prefix so a long-running stream stays bounded.
if (this.head > 0 && this.head * 2 >= this.q.length) {
this.q = this.q.slice(this.head);
this.head = 0;
}
return this.q.length - this.head;
}
}
Template connection
The same time-window queue as the hit counter, with a 3000 ms gap. ping(t) enqueues t and drops the front while front < t - 3000. Calls are strictly increasing, so the stale end is always the front.
Reflection
ping(t)drops calls older thant - 3000. Is the call sitting on the boundary kept? Is the test<or<=?- Time only moves forward. The queue length is the answer. The same
ttwice counts as two calls. - The first ping returns 1. 3000 ms later the old call falls off and the new one stays.