Moving Average from Data Stream
Moving Average from Data Stream
QueueDesign
Problem Statement
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 lastsizeelements of the stream.
Example
Example 1:
Operation Sequence (size = 3):
next(1)returns: 1.000
next(10)returns: 5.500
next(3)returns: 4.667
next(5)returns: 6.000
Solution
A queue is a natural fit for this problem, as it allows us to easily maintain a sliding window of the most recent elements. We also keep a running sum to avoid recalculating the sum of the window every time.
Algorithm Steps
- Initialize a queue and a variable for the running sum.
- When a new value arrives, add it to the queue and the running sum.
- If the queue size exceeds the window size, remove the oldest element from the queue and subtract it from the running sum.
- The moving average is the running sum divided by the current number of elements in the queue.
Window (Queue)
State
Sum: 0
Average: 0.000
Start with an empty queue and sum = 0.
Moving Average from Data Stream Solution