Moving Average from Data Stream solution explained

Moving Average from Data Stream asks for a class that takes numbers one at a time and returns the average of the last size numbers after each one, or of all of them while fewer have arrived. Keep the window in a queue or a circular buffer and a running sum: add the new value, subtract the one that falls out, divide by the current count. Each call is O(1) time and the structure uses O(size) memory.

By Published 8 min read

The problem, in plain terms

A sensor sends one integer reading at a time. Build a class that is created with a window size and has one method, next(value). Each call records the reading and returns the average of the newest size readings. While fewer than size readings exist, average all of them. Results are floating-point numbers.

call  reading  window after call   average
1     6        [6]                 6.0
2     -2       [6, -2]             2.0
3     11       [6, -2, 11]         5.0
4     4        [-2, 11, 4]         4.333...
5     4        [11, 4, 4]          6.333...
6     0        [4, 4, 0]           2.666...
A window of 3 over six readings, made up for this page

The first two calls show the partial window: after call 2 the answer is (6 - 2) / 2, not (6 - 2) / 3. From call 4 on, each new reading pushes the oldest one out. Negative readings are allowed here; make sure your code does not assume otherwise.

Worth asking before you code: can readings be negative or fractional? How large can size be, and how many calls will there be? Should the result be rounded? Is the window measured in readings or in time? The last question changes the problem, and it is a common follow-up.

What the interviewer is looking for

Few people get this one wrong outright, so the signal is in the details: whether you avoid re-adding the whole window on every call, whether you handle the partial window, whether you know that a running floating-point sum can drift, and how you talk about the time-based variant. It is also a quick check that you can write a small class cleanly, with state in the constructor and no global variables.

Brute force: recompute every time

Append every reading to a list and, on each call, sum the last size elements. It is obviously correct, which makes it the reference the faster versions were tested against, but each call costs O(size) and the list keeps every reading ever seen.

class SlowMovingAverage:
    def __init__(self, size):
        self.size = size
        self.readings = []

    def next(self, value):
        self.readings.append(value)
        window = self.readings[-self.size:]
        return sum(window) / len(window)
Python: slice and sum. O(size) per call, O(calls) memory.

Optimal approach: a queue and a running sum

Keep only the readings inside the window, in a double-ended queue, and keep their sum in a variable. When a reading arrives, add it to the sum and append it. If the queue now holds more than size readings, pop the oldest from the front and subtract it. The average is the sum divided by the length of the queue, which handles the partial window with no special case.

from collections import deque


class MovingAverage:
    def __init__(self, size):
        self.size = size
        self.window = deque()
        self.total = 0

    def next(self, value):
        self.window.append(value)
        self.total += value
        if len(self.window) > self.size:
            self.total -= self.window.popleft()
        return self.total / len(self.window)
Python: deque plus running sum. O(1) per call, O(size) memory.

Python's deque pops from the left in O(1). A plain list with pop(0) would shift every remaining element and quietly bring back O(size) per call, which is the kind of detail interviewers like to ask about.

A ring buffer, no queue needed

Since the window never holds more than size readings, a fixed array of that length is enough. Keep a write position that wraps around with modulo and a count of readings seen. The slot you are about to overwrite holds exactly the reading that is leaving the window, so subtract it before writing. This version allocates once, which is why it is the usual choice in embedded code and in languages without a built-in deque. JavaScript arrays do have shift(), but it is not guaranteed to be constant time.

class MovingAverage {
  constructor(size) {
    this.buf = new Array(size).fill(0);
    this.size = size;
    this.pos = 0;
    this.count = 0;
    this.total = 0;
  }

  next(value) {
    this.total += value - this.buf[this.pos]; // the old slot is 0 until the buffer wraps
    this.buf[this.pos] = value;
    this.pos = (this.pos + 1) % this.size;
    if (this.count < this.size) this.count++;
    return this.total / this.count;
  }
}
JavaScript: circular buffer with a running sum. O(1) per call, O(size) memory.

Pre-filling the array with zeros is what lets the first size calls subtract without a branch: the slot being overwritten holds 0 until the buffer has wrapped once.

A note on floating-point drift

With integer readings the running sum is exact in Python, and in JavaScript it stays exact as long as it remains within the safe integer range (about nine quadrillion). With fractional readings, every add and subtract rounds, and after millions of calls the running sum can wander away from the true sum of the window. Two standard fixes: recompute the sum from the buffer every so often, or keep the sum with compensated (Kahan) summation. Mentioning this, even briefly, separates a careful answer from a memorized one.

Complexity summary

k is the window size and n the number of calls
ApproachTime per callMemoryNote
Slice and sumO(k)O(n)Reference only
Deque and running sumO(1)O(k)Shortest correct answer in Python
Ring buffer and running sumO(1)O(k)One allocation, any language
List with pop(0)O(k)O(k)Looks O(1), is not
k is the window size and n the number of calls. Scroll sideways on a small screen.

Edge cases to try

  • Window size 1: every call returns the reading itself.
  • Fewer calls than the window size: divide by the count so far.
  • Negative readings, and readings that cancel to a sum of 0.
  • Many calls with a large window, to make sure nothing grows beyond size.
  • The same reading repeated: the average should not move.

Mistakes to avoid

  • Dividing by size before the window is full.
  • Subtracting the outgoing value after overwriting its slot in the ring buffer, so the new value is subtracted instead.
  • Using integer division in a language where / on two integers truncates, such as C++ or Java.
  • Recomputing sum(window) inside next and calling it O(1) because the window is "small".
  • Storing every reading forever when only the last size are needed.

Follow-ups

  • Average over the last t seconds instead of the last k readings. Store (time, value) pairs in the deque and pop from the front while the oldest is outside the time window. The count now varies, so keep it alongside the sum.
  • Exponential moving average. Keep one number: avg = alpha × value + (1 - alpha) × avg. Constant memory, no window, and older readings fade gradually instead of dropping off a cliff.
  • Moving median. A sum no longer helps. The standard answer is two heaps (a max-heap for the lower half, a min-heap for the upper half) with lazy deletion of values that left the window, at O(log k) per call.
  • Moving maximum. Keep a deque of indexes whose values decrease from front to back; the front is the maximum. Each index enters and leaves once, so it is O(1) amortized.
  • Many independent streams. Keep one structure per stream id in a hash map, and think about evicting idle streams.

How to explain it out loud

Fictional example

From brute force to a running sum in three sentences
Candidate
The naive version sums the last k readings on each call, which is O(k). But between two calls the window only changes by one value in and at most one value out.
Candidate
So I keep the window in a deque and its sum in a variable. Add the new value, and if the deque is longer than k, pop the oldest and subtract it. Divide by the deque's length, which also covers the partial window.
Interviewer
Anything that could go wrong over a very long stream?
Candidate
With integer readings, no. With floats, the running sum accumulates rounding error, so I would recompute it from the window now and then, or use compensated summation.

Logger Rate Limiter keeps a queue of recent events for a different reason, to decide what is still blocked. Longest Substring Without Repeating Characters is the sliding window in its variable-size form. Single-Threaded CPU and IPO move on to heaps, which is where the moving median follow-up leads.

Practicing it with Natively

Questions this short are often paired with a harder follow-up, and practice is where you find out whether you can talk through the time-based window or the moving median without stalling. On Mac or Windows, Natively can transcribe a mock round so you can reread how you explained the running sum, and it can read the prompt from a screenshot to propose a solution to compare with your own. The AI interview assistant page describes how practice sessions work.

Questions people ask

How do you solve Moving Average from Data Stream?

Keep the last size values in a queue or ring buffer and their sum in a variable. On each call add the new value, remove and subtract the oldest if the window is over size, and divide the sum by the number of values held.

What is the time complexity of Moving Average from Data Stream?

O(1) per call and O(size) memory with a running sum. Recomputing the sum of the window on every call is O(size) per call.

What do you divide by before the window is full?

By the number of values received so far, not by the window size. Dividing the sum by the queue's current length handles this without a special case.

Does a running sum cause floating-point errors?

With integer inputs, no, as long as the sum stays in range. With fractional inputs, rounding error can build up over a long stream, so recompute the sum from the window occasionally or use compensated summation.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP