All problems

Moving Average from Data Stream

Easy · queue

Numbers arrive one at a time in a stream, in the order given by values. After each number arrives, report the average of the most recent size numbers. While fewer than size numbers have arrived, the average is taken over all the numbers so far.

Return a list with one average for every arriving number, in order.

Averages are rarely whole, so round each one to 5 decimal places (a value exactly halfway between two candidates rounds up). Your answer is compared with the expected one exactly.

Examples

Example 1

Input: size = 3, values = [1, 10, 3, 5]

Output: [1.0, 5.5, 4.66667, 6.0]

The averages are 1/1, (1 + 10)/2, (1 + 10 + 3)/3 and then only the last three numbers count: (10 + 3 + 5)/3 = 6.

Example 2

Input: size = 1, values = [4, -2, 7]

Output: [4.0, -2.0, 7.0]

With a window of one number, every average is just the newest number.

Example 3

Input: size = 10, values = [2, 3]

Output: [2.0, 2.5]

Fewer than size numbers have arrived, so each average uses everything so far.

Constraints