Search⌘ K
AI Features

Solution: Moving Average from Data Stream

Explore how to implement a MovingAverage class that calculates the average of the last size values in a stream using a queue and a running sum. Learn to maintain constant time complexity for each operation, managing the sliding window efficiently, and understand the space and time tradeoffs involved in this common custom data structure problem.

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:

  • 11 \leq size ...