Problem 298733 · easy · Phase 02 Linear Data Structures

Moving Average of a Stream

queues · deque · class design

Design a class MovingAverage that reports the average of the most recent values in a stream.

  • MovingAverage(size): the window holds at most size values.
  • next(val): append val to the stream and return the average (a float) of the last size values, or of all values seen so far if there are fewer than size.

Examples

Input:  ops  = ["MovingAverage", "next", "next", "next", "next"]
        args = [[3], [1], [10], [3], [5]]
Output: [None, 1.0, 5.5, 4.666666666666667, 6.0]
Explanation: (1)/1, (1+10)/2, (1+10+3)/3, then the window drops 1: (10+3+5)/3.

Constraints

  • 1 <= size <= 1000
  • At most 10**4 calls to next
  • Target: O(1) per call (do not re-sum the window each time)

Goals

  • Maintain a running sum alongside a bounded deque
  • Return an average over fewer than `size` values while the window fills
Starting Python…