← Questions
Moving average from a data stream
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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— addsvaland 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^5calls. Each call must take O(1) time. - Values may be negative or fractional.
Clarifying questions
- Before
sizevalues 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
sizevalues 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
kin one pass with a sliding sum. - Tests:
size = 1, fewer values thansize, negative values.
Follow-ups
- Given a whole array and
k, return the average of every window of lengthk. - 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
