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 size
  • double 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
Moving Average: Sliding Window VisualizationThe Sliding Window ConceptLike a moving frame that shows only the last N values🎯 Goal: Calculate average in O(1) time using queue + running sum✅ Add new values, remove old ones, maintain sum efficientlyStep-by-Step Process (Window Size = 3):Step 1: Add 1Queue: [1]Sum: 1, Avg: 1.01Step 2: Add 10Queue: [1, 10]Sum: 11, Avg: 5.5110Step 3: Add 3Queue: [1, 10, 3]Sum: 14, Avg: 4.671103Window Full!Step 4: Add 5Remove: 1, Add: 5Queue: [10, 3, 5]Sum: 18, Avg: 6.011035RemovedAdded⚡ Algorithm Benefits✅ O(1) time per operation✅ O(window_size) space✅ Real-time processing✅ No redundant calculationsPerfect for data streams!🎯 Key Insight: Maintain running sum + use queue for O(1) sliding window operations
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

n
2n
Linear Growth
Space Complexity
O(size)

Queue stores at most 'size' elements for the sliding window

n
2n
Linear Space

Constraints

  • 1 ≤ size ≤ 1000
  • -105 ≤ val ≤ 105
  • At most 104 calls will be made to next
  • Window size is fixed after initialization
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 25 Bloomberg 22
89.2K Views
High Frequency
~15 min Avg. Time
1.8K 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