Skip to content
DSA Patterns
Menu
Language
Queue & DequeLC #3462 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.

Moving Average from Data Stream

Problem (restated)

Given window size, stream integers via next(val). Return the average of the last at most size values.

Intuition

Queue holds the window; maintain running sum; drop oldest when full.

Approaches

Fixed-size window queue

Unverified
Time O(1) nextSpace O(size)

Idea. Enqueue val, add to sum; if count > size dequeue and subtract; return sum/count.

Walkthrough. size=3: 1 → 1; 10 → 5.5; 3 → 4.666…; 5 → 6.

Trade-offs. Circular buffer avoids shift costs in some languages.

Solution
export class MovingAverage {
  private size: number;
  private buf: number[];
  private pos = 0;
  private count = 0;
  private sum = 0;
  constructor(size: number) {
    this.size = size;
    this.buf = new Array(size);
  }
  next(val: number): number {
    if (this.count === this.size) {
      this.sum -= this.buf[this.pos]!;
    } else {
      this.count++;
    }
    this.buf[this.pos] = val;
    this.sum += val;
    this.pos = (this.pos + 1) % this.size;
    return this.sum / this.count;
  }
}
export class MovingAverage {
  private size: number;
  private buf: number[];
  private pos = 0;
  private count = 0;
  private sum = 0;
  constructor(size: number) {
    this.size = size;
    this.buf = new Array(size);
  }
  next(val: number): number {
    if (this.count === this.size) {
      this.sum -= this.buf[this.pos]!;
    } else {
      this.count++;
    }
    this.buf[this.pos] = val;
    this.sum += val;
    this.pos = (this.pos + 1) % this.size;
    return this.sum / this.count;
  }
}

Template connection

A FIFO of the last size values plus a running sum. When the queue grows past size, subtract and drop the front. next returns sum / count for the values still stored.

Reflection

  • Once the window is full, drop the oldest value from the sum. Do you divide by size, or by how many values you have actually seen?
  • The first calls are shorter than the window. Dividing by size makes those averages too small.
  • Negative values stay in the sum. This average is not an integer division.
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

Moving average, window size 3. Queue holds the last at most 3 values; keep a running sum.

·
0
·
1
·
2

size = 3 · sum = 0

Key:CurrentActive rangeMatchSettled