Search⌘ K
AI Features

Problem: Moving Average from Data Stream

Explore how to implement a moving average calculation over a sliding window of integers from a data stream using a queue. Understand maintaining a running sum for O(1) update time and handling window size constraints to compute averages efficiently in C++.

Statement

Given a stream of integers and a window size, calculate the moving average of all integers within the sliding window.

Implement the MovingAverage class:

  • MovingAverage(int size): Initializes the object with the window size size.

  • double next(int val): Accepts a new integer val from the stream and returns the moving average of the most recent size values seen so far.

Note: If fewer than size values have been received so far, the moving average is computed over all the values received up to that point.

Constraints:

  • 11 \leq size 1000\leq 1000

  • ...