Rolling Mean Over the Latest K Readings
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a rolling-window mean over a stream of readings, handling the warm-up phase and keeping floating-point error from accumulating across long streams.
Rolling Mean Over the Latest K Readings
A monitoring service receives numeric readings one at a time. After each reading arrives, it must report the arithmetic mean of the most recent readings, looking back at most size of them.
You are given the window length and a recorded script of calls to replay. Process the calls in order and return the value produced by each call.
Function
moving_average(size, operations, arguments) -> List[float]
sizeis the maximum number of readings that contribute to a mean.operationsis a list of strings. Each entry must be"next".argumentsis a list of lists with the same length asoperations. For thei-th call, the new reading isarguments[i][0].
Behavior
- Each
"next"call adds the reading to the stream and produces one number: the mean of the latestmin(n, size)readings, wherenis the count of readings received so far, including the current one. - Until
sizereadings have arrived, the mean is taken over all readings received so far (divide by the current count, not bysize). - Once more than
sizereadings have arrived, the oldest reading drops out of the window. - If any entry of
operationsis not"next", raise aValueError. - Return a list with one mean per call, in call order.
Precision
Streams may be very long and contain readings of widely differing magnitudes. A running total that is repeatedly added to and subtracted from can lose small contributions permanently. For example, with size = 2 and readings 1e16, 1.0, 1.0, the final mean should be 1.0. Your solution should keep the result accurate in such cases, while spending only constant work per reading (amortized).
Constraints
1 <= size <= 10^6len(operations) == len(arguments), and eacharguments[i]contains at least one number.- The number of calls may be much larger than
size. - Readings are finite floating-point numbers and may be negative.
- Aim for O(1) amortized time per call.
Examples
Example 1
Input: moving_average(3, ['next', 'next', 'next', 'next'], [[1], [10], [3], [5]])
Output: [1, 5.5, 4.666666666666667, 6]
Example 2
Input: moving_average(1, ['next', 'next', 'next'], [[2.5], [-4], [7.25]])
Output: [2.5, -4, 7.25]
Example 3
Input: moving_average(4, ['next', 'next'], [[10], [-2]])
Output: [10, 4]
Hints
Hint 1
The mean is the window total divided by the current window length. Recomputing the total from scratch every call is too slow when size is large, so maintain it incrementally.
Hint 2
Keep the readings currently in the window in a FIFO queue. After appending a new reading, if the queue is longer than size, remove the oldest one and take it out of the total.
Hint 3
A plain running total can permanently lose small values after a huge one passes through. Track a second variable holding the rounding error of each addition (compensated, Neumaier-style summation), treating removal as adding the negative, and combine both parts with math.fsum when producing each mean.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The mean of the window is window_sum / window_length, so the goal is to keep the window sum current in constant time per call.
- Keep the readings in the window in a FIFO queue (
deque). - On each call, append the new reading and add it to a running total.
- If the queue now has more than
sizeitems, pop the oldest and subtract it from the total. - Output
total / len(window).
Because the queue length is used as the divisor, the warm-up phase (fewer than size readings) is handled automatically.
Numerical stability
Adding and subtracting in a plain float total keeps every rounding error forever. With size = 2 and the stream 1e16, 1.0, 1.0, the 1.0 values are rounded away while 1e16 is in the window. After 1e16 leaves, the plain total is 0.0 instead of 2.0.
To avoid this, use Neumaier (Kahan-Babuska) compensated summation. Alongside total, keep a correction variable. For each addition total + value, the rounding error equals (larger - new_total) + smaller, where "larger" is the operand with greater magnitude. That error is accumulated in correction. Removing an old reading is just adding its negation, so the same update is used. Each mean is computed as math.fsum((total, correction)) / len(window).
Why it is correct
- Window invariant: after each call the queue holds exactly the last
min(n, size)readings, since one item is appended and at most one removed, and removal happens only when the length exceedssize. - Sum invariant:
total + correctionequals the sum of the window up to a negligible error that does not grow with stream length, since each step's rounding loss is captured incorrection. - An operation other than
"next"raisesValueError.
Complexity
- Time: O(1) amortized per call, so O(N) for N calls.
- Space: O(min(N, size)) for the window, plus O(N) for the output list.
Reference solution
from collections import deque
import math
from typing import List
def moving_average(size: int, operations: List[str], arguments: List[List[float]]) -> List[float]:
window = deque()
total = 0.0
correction = 0.0
result = []
def add_to_sum(value):
nonlocal total, correction
new_total = total + value
if abs(total) >= abs(value):
correction += (total - new_total) + value
else:
correction += (value - new_total) + total
total = new_total
for operation, args in zip(operations, arguments):
if operation != "next":
raise ValueError("unsupported operation")
value = float(args[0])
window.append(value)
add_to_sum(value)
if len(window) > size:
add_to_sum(-window.popleft())
result.append(math.fsum((total, correction)) / len(window))
return result