Skip to content
DSA Patterns
Menu
Language
Queue & DequeLC #9336 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time O(1) amortizedSpace O(w)

Idea. 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.

Solution
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 than t - 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 t twice counts as two calls.
  • The first ping returns 1. 3000 ms later the old call falls off and the new one stays.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

ping(t) records a call at time t. Return how many calls sit in [t-3000, t].

window = 3000ms

Key:CurrentActive rangeMatchSettled