İçeriğe atla
ΣDSA Patterns
Menü
Dil

Kuyruk ve Deque

Rehber 6 / 6 · Yol 6 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

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

Tested only
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[] = [];
  ping(t: number): number {
    this.q.push(t);
    while (this.q[0]! < t - 3000) this.q.shift();
    return this.q.length;
  }
}
export class RecentCounter {
  private q: number[] = [];
  ping(t: number): number {
    this.q.push(t);
    while (this.q[0]! < t - 3000) this.q.shift();
    return this.q.length;
  }
}

Template connection

Queue & Deque recent-event tracking.

Reflection