Solution: Moving Average from Data Stream
Let’s solve the Moving Average from Data Stream problem using the Custom Data Structures pattern.
We'll cover the following
Statement
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement a class called MovingAverage
that has the following methods:
Constructor (int size): This constructor initializes the object with the specified window size.
double next (int val): This method takes an integer value as input and returns the moving average of the last
size
values from the stream.
Constraints:
size
val
At most
calls can be made to next.
Solution
The algorithm calculates the moving average of the most recent values within a fixed-size window. It employs a queue to store these values and maintains a running sum for efficient computation. Each time a new value is added to the window, it is appended to the queue, and the running sum is updated accordingly. If the queue exceeds the specified size (i.e., the window is full), the oldest value is removed from the queue, and the sum is adjusted by subtracting this value. The moving average is then calculated by dividing the running sum by the number of values in the queue. This approach ensures that the moving average is updated, achieving constant time complexity for each operation.
Constructor: The constructor initializes the following variables:
size
: This represents the window size, the maximum number of recent values for calculating the moving average.queue
: A queue data structure stores the most recent values up to the specified window size. The queue supports efficient operations for adding new values to the end and removing the oldest value from the front, essential for maintaining the sliding window.window_sum
: This keeps a running sum of the values currently in the window. This allows the moving average to be calculated efficiently without the need to sum all values repeatedly.
The
next
method: Thenext
method calculates the moving average by following these steps:Enqueue the new value (
val
) toqueue
and add it towindow_sum
. This effectively extends the current sliding window to include the new value.If the number of elements in
queue
exceedssize
(indicating the window is full), remove the oldest value fromqueue
and updatewindow_sum
by subtracting this value. This ensures the queue size stays within the specified window size.Compute the moving average as
window_sum / len(queue)
. Use floating-point division to ensure the result is a float.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.