Moving Average from Data Stream
Easy
Topics
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
MovingAverage(size) creates the object with the window size. next(val) appends val and returns the average of the last size values — or of everything so far, while fewer than size values have arrived.
Return each average rounded to five decimal places, so the result is unambiguous.
Example 1
Input: operations = ["MovingAverage","next","next","next","next"], values = [[3],[1],[10],[3],[5]] Output: [null,1.00000,5.50000,4.66667,6.00000] Explanation: After 1 and 10 the window is not yet full, so the averages are over 1 and 2 values. The third is (1+10+3)/3 and the fourth drops the 1.
Constraints
- 1 <= size <= 1000
- -10^5 <= val <= 10^5
- At most 10^4 calls to next.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Recomputing the sum of the window on every call re-reads values that have not changed. Only two things change when a value arrives: one enters the window, and once the window is full one leaves it.
So carrying a running sum turns each call into one addition and at most one subtraction, and the only thing the structure has to remember is which value is due to leave next — which is exactly what a queue answers.
Approach
- Keep a queue of the values currently in the window and a running sum of them.
- On
next(val), pushvaland add it to the sum. - If the queue now holds more than
sizevalues, pop the front and subtract it from the sum. - Return the sum divided by the current queue length — not by
size, which would be wrong while the window is still filling.
Walkthrough
size = 3
next(1) queue [1] sum 1 1 / 1 = 1.00000
next(10) queue [1,10] sum 11 11 / 2 = 5.50000
next(3) queue [1,10,3] sum 14 14 / 3 = 4.66667
next(5) full: drop the 1
queue [10,3,5] sum 18 18 / 3 = 6.00000Complexity
- Time — O(1): one push, at most one pop, and a division per call.
- Space — O(size): the queue never holds more than the window size.
Common Pitfalls
- Dividing by
sizerather than by the number of values actually in the window gives wrong answers for the first few calls. - Letting the running sum drift by popping without subtracting is the classic bug; the sum and the queue have to change together.
Full Solution — all languages
class MovingAverage:
def __init__(self, size):
from collections import deque
self.size = size
self.window = deque()
self.total = 0
def next(self, val):
self.window.append(val)
self.total += val
if len(self.window) > self.size:
self.total -= self.window.popleft()
return self.total / len(self.window)import java.util.*;
class MovingAverage {
private final int size;
private final Deque<Integer> window = new ArrayDeque<>();
private long total = 0;
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
window.addLast(val);
total += val;
if (window.size() > size) total -= window.pollFirst();
return (double) total / window.size();
}
}#include <bits/stdc++.h>
using namespace std;
class MovingAverage {
public: MovingAverage(int size) : size_(size), total_(0) {
}
double next(int val) {
window_.push_back(val);
total_ += val;
if ((int)window_.size() > size_) {
total_ -= window_.front();
window_.pop_front();
}
return (double)total_ / (double)window_.size();
}
private: int size_;
long long total_;
deque<int> window_;
};class MovingAverage {
constructor(size) {
this.size = size;
this.window = [];
this.head = 0;
this.total = 0;
}
next(val) {
this.window.push(val);
this.total += val;
if (this.window.length - this.head > this.size) {
this.total -= this.window[this.head];
this.head++;
}
return this.total / (this.window.length - this.head);
}
}