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 from Data Stream INPUT Window Size = 3 Data Stream: 1 10 3 5 stream direction Sliding Window (Queue): [ ] [ ] [ ] Max 3 elements Operations: MovingAverage(3) next(1), next(10) next(3), next(5) ALGORITHM STEPS 1 Initialize Queue Create empty queue, sum=0 2 Add New Value Push val to queue, sum+=val 3 Check Window Size If queue.size > k: pop front 4 Calculate Average Return sum / queue.size Execution Trace: Val Queue Avg 1 [1] 1.0 10 [1,10] 5.5 3 [1,10,3] 4.67 5 [10,3,5] 6.0 * Row 4: 1 evicted (window full) FINAL RESULT Final Queue State: 10 3 5 front back Sum = 10 + 3 + 5 = 18 Count = 3 Avg = 18 / 3 = 6.0 Output Array: [null, 1.0, 5.5, 4.666666666666667, 6.0] null = constructor return OK - Complete! Time: O(1) per next() Key Insight: Use a Queue (FIFO) to maintain the sliding window. Keep a running sum to avoid recalculating the entire sum each time. When window is full, subtract the front element before removing it. This achieves O(1) time complexity for each next() call instead of O(k) with naive approach. TutorialsPoint - Moving Average from Data Stream | Optimal Solution
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