Skip to content
DSA Patterns
Menu
Language
Queue & DequeLC #3623 of 6← PreviousNext →

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

Design Hit Counter

Problem (restated)

Record hits at integer timestamps (seconds). getHits(t) returns hits in the past 300 seconds inclusive of t (i.e. (t-300, t]).

Intuition

Queue of hit times; on getHits drop timestamps ≤ t-300.

Approaches

Queue of timestamps (300s)

Unverified
Time O(1) amortizedSpace O(hits in window)

Idea. hit enqueues; getHits while front ≤ t-300 dequeue; return size.

Walkthrough. hit 1,2,3; getHits(4)=3; hit 300; getHits(300)=4; getHits(301)=3.

Trade-offs. Bucket arrays of size 300 scale better under high QPS with many hits/sec.

Solution
export class HitCounter {
  private q: number[] = [];
  private head = 0;
  hit(timestamp: number): void {
    this.q.push(timestamp);
  }
  getHits(timestamp: number): number {
    while (this.head < this.q.length && this.q[this.head]! <= timestamp - 300) 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 HitCounter {
  private q: number[] = [];
  private head = 0;
  hit(timestamp: number): void {
    this.q.push(timestamp);
  }
  getHits(timestamp: number): number {
    while (this.head < this.q.length && this.q[this.head]! <= timestamp - 300) 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

Time-window queue: hit enqueues the timestamp, and getHits drops the front while front ≤ t - 300. The length of what remains is the answer. Timestamps only increase, so only the front can expire.

Reflection

  • getHits drops timestamps older than 300 seconds from the front. The window is (t - 300, t].
  • Several hits share a timestamp. One record each, or a counter? What does that change about memory?
  • Time does not go backward. Without that guarantee a queue is not enough.
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

Hit counter: queue of timestamps. getHits(t) counts hits in (t-300, t].

window = 300s

Key:CurrentActive rangeMatchSettled