Moving Average from Data Stream
1 approach, code in every language
Problem description
You receive a stream of integers one value at a time and must report the average of a sliding window of the most recent values.
Implement the MovingAverage class. The constructor MovingAverage(size) fixes the window width. The method next(val) appends val to the stream and returns the average of the last size values seen so far.
Before the stream has produced size values, the average is taken over however many values have arrived.
Example 1
Input: ["MovingAverage","next","next","next","next"] [[3],[1],[10],[3],[5]]
Output: [null,1.0,5.5,4.66667,6.0]
Window size 3. next(1) averages [1] = 1.0; next(10) averages [1,10] = 5.5; next(3) averages [1,10,3] = 4.66667; next(5) drops 1 and averages [10,3,5] = 6.0.
Example 2
Input: ["MovingAverage","next","next"] [[1],[4],[8]]
Output: [null,4.0,8.0]
With window size 1 each call reports only the latest value, so next(4) = 4.0 and next(8) = 8.0.
Constraints
1 <= size <= 1000-10^5 <= val <= 10^5At most 10^4 calls will be made to next.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free