Moving Average from Data Stream

Easy

Topics
ArrayQueueDesignData Stream

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

returnsMovingAverage(3)next(1)1.00000next(10)5.50000next(3)4.66667next(5)6.00000
The window holds the last 3 values. While fewer than that have arrived the average is over however many there are, not over 3 — which is why the first calls are not divided by the window size. Each answer is rounded to five decimal places.
Calls run top to bottom; the arrow shows what each one returns.
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

  1. Keep a queue of the values currently in the window and a running sum of them.
  2. On next(val), push val and add it to the sum.
  3. If the queue now holds more than size values, pop the front and subtract it from the sum.
  4. 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.00000

Complexity

  • 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 size rather 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)
SensAI
Beta
Tap the mic to stop voice mode