Moving average from a stream
Challenge · Write code · about 15 min
Numbers arrive one at a time in values. After each number, report the average of the last size numbers (or of all numbers so far, while fewer than size have arrived).
Return the list of averages. Each update must take O(1) time, so do not re-add the whole window.
Example 1
Input:
[3,[1,10,3,5]]
Output:
[1,5.5,4.666666666666667,6]
When 5 arrives, 1 leaves the window. The average is (10 + 3 + 5) / 3 = 6.
Example 2
Input:
[2,[4,8,6,6]]
Output:
[4,6,7,6]
Constraints
- 1 ≤ size ≤ 1, 000
- 1 ≤ values.length ≤ 10, 000
- -10, 000 ≤ values[i] ≤ 10, 000
- Answers within 10^-6 are accepted
Learn the idea first: Queues: enqueue, dequeue; circular buffer, a visual lesson.
More Queues: enqueue, dequeue; circular buffer problems
- Which value leaves first? Warm-up
- Predict head and tail Warm-up
- Implement a circular queue Standard
- Number of recent calls Standard
- Spot the bug: the tail runs off the end Standard