Moving Average from Data Stream
Beginner Mode

Problem Statement

Given a stream of integers and a window size size, compute the average of the last size values each time a new value arrives.

If fewer than size values have been seen so far, compute the average of all values seen.

Implement the MovingAverage class:

  • MovingAverage(int size) initializes the object with the window size.
  • float next(int val) adds val to the stream and returns the average of the last size values (or all values if fewer than size have been added).

Additional information

  • 1 <= size <= 1000
  • -100,000 <= val <= 100,000
  • At most 10,000 calls will be made to next.

Example 1:

Input:
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]

Output: [null, 1.0, 5.5, 4.66667, 6.0]

Explanation:

  • MovingAverage(3) -- window size is 3
  • next(1) -- stream: [1], average = 1/1 = 1.0
  • next(10) -- stream: [1, 10], average = 11/2 = 5.5
  • next(3) -- stream: [1, 10, 3], average = 14/3 = 4.66667
  • next(5) -- stream: [10, 3, 5] (window of 3), average = 18/3 = 6.0

Example 2:

Input:
["MovingAverage", "next", "next"]
[[1], [5], [10]]

Output: [null, 5.0, 10.0]

Explanation: Window size is 1, so each call just returns the latest value.

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →