Moving Average from Data Stream

Sliding window average — fixed-size deque holding the last k values, maintain a running sum.

Easy
Time O(1) per next Space O(size)
LeetCode
2 min read
design sliding-window queue

Problem#

Implement a moving average over a stream: next(val) returns the average of the last up-to-size values seen.

Examples#

  • size=3; next(1)1, next(10)5.5, next(3)4.667, next(5)6.

Constraints#

  • 1 <= size <= 1000, up to 10^4 calls.

Approach#

Fixed-capacity queue (deque). On next, push the new value and add to a running sum; if size exceeded, pop the front and subtract.

Solution#

Moving Average
class MovingAverage {
deque<int> q;
int sz;
long long sum = 0;
public:
MovingAverage(int size) : sz(size) {}
double next(int val) {
q.push_back(val);
sum += val;
if ((int)q.size() > sz) {
sum -= q.front();
q.pop_front();
}
return (double)sum / q.size();
}
};

Editorial#

A running sum avoids re-summing the window each call. Once the deque hits capacity, every push pairs with a pop — strict sliding window in O(1).

Complexity#

  • Time: O(1) per next.
  • Space: O(size).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.