Problem 298733 · easy · Level 02 Linear Data Structures

A Steady Speedometer Readout

queues · deque · class design

A bike computer smooths its speed display so the number on the screen does not jump about: it shows the mean of the latest few raw readings. Write the class MovingAverage that does the smoothing.

  • MovingAverage(size): the display averages at most the latest size readings.
  • next(val): take in the new reading val and return what the display now shows, as a float: the mean of the latest size readings, or of every reading so far while fewer than size have arrived.

Examples

Input:  ops  = ["MovingAverage", "next", "next", "next", "next", "next"]
        args = [[3], [4], [7], [1], [10], [-2]]
Output: [None, 4.0, 5.5, 4.0, 6.0, 3.0]
Explanation: 4/1, (4+7)/2, (4+7+1)/3, then the window drops 4: (7+1+10)/3, then it drops 7: (1+10-2)/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…