15% off all plans & roadmaps Use code
See plansLeetCode 346 · Solution & editorial
You are given a class MovingAverage that receives a stream of integers. Initialize the object with an integer size, representing the size of a moving window. Implement the next(val) method, which accepts an integer val and returns the moving average of the last size values in the stream (including the current val). If the number of elements seen so far is less than size, compute the average of all elements received so far.
Moving Average from Data Stream is a Sliding Window problem, in the Fixed Size (Subarray Calculation) subpattern. The pattern covers fixed-size, variable-size, and character frequency matching window techniques
Learn fixed-size sliding window for subarray calculations like maximum average, moving average, and k-size subarray problems.
The reference solution runs in O(N) time and O(K) space.
Moving Average from Data Stream has been reported in interviews at Google, Apple, Spotify, Indeed, Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Moving Average from Data Stream is a Sliding Window problem, in the Fixed Size (Subarray Calculation) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.