KatInterview

Rolling Mean Over the Latest K Readings

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designsliding-windowqueuefloating-point

Last 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]
  • size is the maximum number of readings that contribute to a mean.
  • operations is a list of strings. Each entry must be "next".
  • arguments is a list of lists with the same length as operations. For the i-th call, the new reading is arguments[i][0].

Behavior

  • Each "next" call adds the reading to the stream and produces one number: the mean of the latest min(n, size) readings, where n is the count of readings received so far, including the current one.
  • Until size readings have arrived, the mean is taken over all readings received so far (divide by the current count, not by size).
  • Once more than size readings have arrived, the oldest reading drops out of the window.
  • If any entry of operations is not "next", raise a ValueError.
  • 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^6
  • len(operations) == len(arguments), and each arguments[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.