Moving average of a stream

A code exercise of about 15 minutes: read the statement, solve «Moving average of a stream» in the browser and get a review like in a real interview.

Code · 15 min
Loading…

Statement

A sensor sends numbers one at a time. Write movingAverage(k, values): for each value that arrives, compute the average of the last k received (or of all of them while there are fewer than k), and return the list of averages, one per value. k ≥ 1 and can be big: each new value must cost O(1), not O(k). Use a ring buffer of size k and a running sum.