Moving Average from Data Stream Problem
#346
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 346.
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage class:
MovingAverage(int size)Initializes the object with the size of the windowsize.double next(int val)Returns the moving average of the lastsizevalues of the stream.
Example 1:
Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]
Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Constraints:
1 <= size <= 1000-10^5 <= val <= 10^5- At most
10^4calls will be made tonext.
Solution
Approach: Circular Buffer with a Running Sum
Summing the whole window on every call costs O(size). Instead, keep a running sum of the values in the window and update it as values come and go.
Store the window in an array of length size used as a circular buffer: the count-th value (counting from 0) goes to index count % size. Once the buffer is full, that index holds the oldest value, which is exactly the one leaving the window.
On each next(val):
- Let
i = count % size. Update the sum withtotal += val - window[i]: add the new value and subtract the one it replaces. While the buffer is still filling up,window[i]is0, so the same line works. - Store
valatwindow[i]and increasecount. - Return
total / min(count, size). Before the window is full, the average is over thecountvalues seen so far, not oversize.
Make sure to divide as floating-point numbers: integer division would turn 5.5 into 5.
Complexity: O(1) time per call and O(size) extra space.
class MovingAverage:
def __init__(self, size: int):
self.window = [0] * size # circular buffer of the last `size` values
self.count = 0 # values seen so far
self.total = 0 # sum of the values in the window
def next(self, val: int) -> float:
i = self.count % len(self.window)
self.total += val - self.window[i] # the new value replaces the oldest one (0 while filling up)
self.window[i] = val
self.count += 1
return self.total / min(self.count, len(self.window))