346. Moving Average from Data Stream
Practice Moving Average from Data Stream for free on NudgeCode: Easy, Sliding Window pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
Design a class that receives a stream of integers and reports the average of the last size values (or of all values so far, if fewer than size have arrived).
MovingAverage(size)sets the window size.next(val)addsvalto the stream and returns the current moving average.
Each test is a list of operations and their arguments; the expected output lists what each call returns (null for the constructor). Answers within 1e-5 are accepted.
Example
["MovingAverage","next","next","next","next"]
[[3],[1],[10],[3],[5]]
-> [null,1.0,5.5,4.66667,6.0]
Constraints
- 1 <= size <= 1000
- -10^5 <= val <= 10^5
- Up to 10^4 calls to
next; aim for O(1) per call