v9.1.1
Menu

Moving Average from Data Stream

easyPRODesign & ImplementationGoogle DSA

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

You will receive the window size and a sequence of values. For each value, output the moving average with 2 decimal places.

Implement a class MovingAverage: MovingAverage(size) sets the window size, and next(val) adds val to the stream and returns the current moving average as a float (the average of all values seen so far while fewer than size have arrived). The tests print each returned value to 2 decimal places.

Example

Input
3
1,10,3,5
Output
1.00
5.50
4.67
6.00
Reasoning
  • Input: the window size k=3k = 3 (the size argument), then the stream 1, 10, 3, 5, one value at a time. After each arrival, the average covers only the most recent values, at most kk of them.
  • Value 1: only one value seen so far, so the window is {1}\{1\} and the average is 11=1.00\frac{1}{1} = 1.00.
  • Value 10: the window is {1,10}\{1, 10\}, still shorter than kk, so divide by 2: 1+102=5.50\frac{1+10}{2} = 5.50.
  • Value 3: the window is now full, {1,10,3}\{1, 10, 3\}: 143=4.666…\frac{14}{3} = 4.666\ldots, shown as 4.67.
  • Value 5: a fourth value exceeds k=3k = 3, so the oldest value, 1, leaves the window. It becomes {10,3,5}\{10, 3, 5\} and the average is 183=6.00\frac{18}{3} = 6.00.
  • Output: one average per arrival, 1.00, 5.50, 4.67, 6.00, each shown to 2 decimal places. Notice the divisor grows 1, 2, 3 and then stays at kk: before the window fills, you divide by how many values have arrived, not by kk.

Constraints

  • 1 <= k <= 1000
  • -10^5 <= val <= 10^5
  • At most 10^4 calls to next

More from Google DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.