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.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI