344. Moving Average from Data Stream

Given a continuous stream of integers and a specified window size, compute the moving average of the last size elements within the sliding window.

Implement the MovingAverage class:

  • MovingAverage(int size): Initializes an object with a sliding window of the given size.
  • double next(int val): Inserts val into the stream and returns the moving average of the most recent size elements.

Example 1:

Input: ["MovingAverage", "next", "next", "next", "next"], [[4], [2], [4], [6], [8]]  

Output: [null, 2.0, 3.0, 4.0, 5.0]  

Explanation:

MovingAverage movingAverage = new MovingAverage(4);  

movingAverage.next(2);  // return 2.0 = 2 / 1  

movingAverage.next(4);  // return 3.0 = (2 + 4) / 2  

movingAverage.next(6);  // return 4.0 = (2 + 4 + 6) / 3  

movingAverage.next(8);  // return 5.0 = (2 + 4 + 6 + 8) / 4  

Example 2:

Input: ["MovingAverage", "next", "next", "next", "next", "next"], [[2], [1], [3], [5], [7], [9]]  

Output: [null, 1.0, 2.0, 4.0, 6.0, 8.0]  

Explanation:

MovingAverage movingAverage = new MovingAverage(2);  

movingAverage.next(1);  // return 1.0 = 1 / 1  

movingAverage.next(3);  // return 2.0 = (1 + 3) / 2  

movingAverage.next(5);  // return 4.0 = (3 + 5) / 2  

movingAverage.next(7);  // return 6.0 = (5 + 7) / 2  

movingAverage.next(9);  // return 8.0 = (7 + 9) / 2  

Now Your Turn!

Pick the correct output for the given input

Input: ["MovingAverage", "next", "next", "next", "next", "next"], [[3], [7], [3], [5], [2], [8]] 

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ size ≤ 10⁴ → The window size (size) will always be at least 1 and at most 10,000.
  • -10⁵ ≤ val ≤ 10⁵ → Each integer in the stream (val) can range from -100,000 to 100,000.
  • At most 10⁴ calls → The next(val) function will be called at most 10,000 times.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class MovingAverage {
public:
MovingAverage(int size) {
// Your code goes here
}
double next(int val) {
// Your code goes here
}
};
Test Case

Input:

Calls
Params