Moving Average from Data Stream - Problem

Design a class to calculate the moving average of a stream of integers over a sliding window of a specified size.

Implement the MovingAverage class:

  • MovingAverage(int size) - Initializes the object with the size of the window.
  • double next(int val) - Returns the moving average of the last size values of the stream.

The moving average is calculated by taking the sum of all values in the current window and dividing by the number of values in the window.

Input & Output

Example 1 — Basic Moving Average
$ Input: operations = [["MovingAverage",3],["next",1],["next",10],["next",3],["next",5]]
Output: [null,1.0,5.5,4.666666666666667,6.0]
💡 Note: Initialize with window size 3. Add 1 → avg=1.0, add 10 → avg=(1+10)/2=5.5, add 3 → avg=(1+10+3)/3=4.67, add 5 → avg=(10+3+5)/3=6.0
Example 2 — Single Element Window
$ Input: operations = [["MovingAverage",1],["next",2],["next",8]]
Output: [null,2.0,8.0]
💡 Note: Window size 1 means only current value matters. Add 2 → avg=2.0, add 8 → avg=8.0
Example 3 — Larger Window
$ Input: operations = [["MovingAverage",5],["next",1],["next",2],["next",3]]
Output: [null,1.0,1.5,2.0]
💡 Note: Window size 5 but only 3 values added. Add 1 → avg=1.0, add 2 → avg=(1+2)/2=1.5, add 3 → avg=(1+2+3)/3=2.0

Constraints

  • 1 ≤ size ≤ 1000
  • -105 ≤ val ≤ 105
  • At most 104 calls to next

Visualization

Tap to expand
Moving Average: Sliding Window of Size 3Input Stream11035Step-by-step ProcessingAdd 1: Window=[1] → Avg = 1/1 = 1.0Add 10: Window=[1,10] → Avg = 11/2 = 5.5Add 3: Window=[1,10,3] → Avg = 14/3 = 4.67Add 5: Window=[10,3,5] → Avg = 18/3 = 6.0Final Output[null, 1.0, 5.5,4.666..., 6.0]Queue maintains window,running sum avoids recalc
Understanding the Visualization
1
Input Stream
Stream of integers: [1, 10, 3, 5] with window size 3
2
Sliding Window
Maintain last 3 values and calculate their average
3
Output
Return averages: [1.0, 5.5, 4.67, 6.0]
Key Takeaway
🎯 Key Insight: Use a queue to maintain the sliding window and keep a running sum to achieve O(1) time complexity per operation
Asked in
Google 25 Amazon 18 Facebook 12 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen