← Questions

Moving average from a data stream

0
MetaCodingLast asked Jan 2026

A coding interview question asked in Meta's technical phone screen, last asked Jan 2026. It tests queues, sliding window and design.

Numbers arrive one at a time. After each one, return the average of the last size numbers, or of all numbers so far while fewer than size have arrived.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • MovingAverage(size: int) — size >= 1.
  • next(val: float) -> float — adds val and returns the current average.

Example

m = MovingAverage(3)
m.next(1)     ->  1.0
m.next(10)    ->  5.5           # (1 + 10) / 2
m.next(3)     ->  4.666667      # (1 + 10 + 3) / 3
m.next(5)     ->  6.0           # (10 + 3 + 5) / 3; the 1 has left the window

Constraints

  • Up to 10^5 calls. Each call must take O(1) time.
  • Values may be negative or fractional.

Clarifying questions

  • Before size values have arrived, average over what we have, or return nothing?
  • Integer or floating-point values? How much precision is expected?
  • Is this a stream, or do I get the whole array at once?

What a strong answer covers

  • A queue (or a fixed ring buffer) of the last size values plus a running sum. Add the new value, subtract the one that leaves the window.
  • O(1) time per call and O(size) memory.
  • Floating-point drift in the running sum over a very long stream, and how to fix it (integer sums, or recomputing the sum now and then).
  • The array version: return the average of every window of length k in one pass with a sliding sum.
  • Tests: size = 1, fewer values than size, negative values.

Follow-ups

  • Given a whole array and k, return the average of every window of length k.
  • A time-based window: the average of values from the last 60 seconds.
  • Keep the moving median instead of the mean.

Where it's asked

  • Meta · Technical phone screen · Last asked Jan 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

queues · sliding window · design

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding