Moving Average from Data Stream - Problem
You're given a stream of integers and need to efficiently calculate the moving average of all integers within a sliding window of fixed size. This is a common problem in real-time data processing, financial applications, and signal processing.
Design and implement the MovingAverage class with the following methods:
MovingAverage(int size): Initialize the object with the window sizedouble next(int val): Add the new value to the stream and return the moving average of the last size values
Example: If window size is 3 and you receive values [1, 10, 3, 5], the moving averages would be:
- After 1: 1.0 (only one value)
- After 10: 5.5 (average of [1, 10])
- After 3: 4.67 (average of [1, 10, 3])
- After 5: 6.0 (average of [10, 3, 5] - sliding window)
Input & Output
example_1.py — Basic Window Operations
$
Input:
MovingAverage(3)
.next(1) → 1.0
.next(10) → 5.5
.next(3) → 4.666...
.next(5) → 6.0
›
Output:
[1.0, 5.5, 4.666666666666667, 6.0]
💡 Note:
Window size is 3. After adding 1: avg of [1] = 1.0. After 10: avg of [1,10] = 5.5. After 3: avg of [1,10,3] = 4.67. After 5: window slides to [10,3,5], avg = 6.0
example_2.py — Single Element Window
$
Input:
MovingAverage(1)
.next(7) → 7.0
.next(3) → 3.0
.next(9) → 9.0
›
Output:
[7.0, 3.0, 9.0]
💡 Note:
Window size is 1, so each value becomes the complete window and the average is just that value itself
example_3.py — Large Window
$
Input:
MovingAverage(5)
.next(1) → 1.0
.next(2) → 1.5
.next(3) → 2.0
.next(4) → 2.5
.next(5) → 3.0
.next(6) → 4.0
›
Output:
[1.0, 1.5, 2.0, 2.5, 3.0, 4.0]
💡 Note:
Window fills up gradually. First 5 calls fill the window [1,2,3,4,5] with avg 3.0. The 6th call slides window to [2,3,4,5,6] with avg 4.0
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Window
Create a queue (like a conveyor belt) that holds exactly 3 numbers and a running sum counter
2
Add First Numbers
Add 1, then 10. Queue grows: [1] → [1,10]. Running sum: 1 → 11. Averages: 1.0 → 5.5
3
Fill the Window
Add 3. Queue becomes [1,10,3]. Running sum: 14. Average: 4.67. Window is now full!
4
Sliding Window
Add 5. Remove 1 (oldest), add 5 (newest). Queue: [10,3,5]. Sum: 18-1=18. Average: 6.0
Key Takeaway
🎯 Key Insight: Use a queue to maintain the exact window elements and a running sum for O(1) average calculation. When adding: sum += new_val, when removing: sum -= old_val.
Time & Space Complexity
Time Complexity
O(1)
Each next() operation takes constant time - just add/remove and divide
✓ Linear Growth
Space Complexity
O(size)
Queue stores at most 'size' elements for the sliding window
✓ Linear Space
Constraints
- 1 ≤ size ≤ 1000
- -105 ≤ val ≤ 105
- At most 104 calls will be made to next
- Window size is fixed after initialization
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code