Fixed-Window Moving Averages in Linear Time

Medium · Coding & Algorithms · Quantitative Researcher · Onsite

Problem Statement

Given an integer list values and a positive window length window, implement rolling_means(values: List[int], window: int) -> List[float] to compute the arithmetic average of every contiguous subarray of size window in left-to-right order.

Each average in the returned list must be a standard 64-bit float. Whenever values contains fewer than window elements, no full subarray of length window can be formed, so the function must return [].

Because inputs can contain tens of millions of 64-bit signed integers, your algorithm must advance from one window to the next in O(1) time (O(n) overall time) without losing accuracy to floating-point accumulation drift or 64-bit intermediate integer overflow.

def rolling_means(values: List[int], window: int) -> List[float]:
    ...

Examples

Example 1

Input:  values = [4, -2, 7, 1, -5, 8, 2], window = 4
Output: [2.5, 0.25, 2.75, 1.5]

Walk-through of the four contiguous windows of length 4: - [4, -2, 7, 1] sums to 10, giving 10 / 4 = 2.5. - [-2, 7, 1, -5] sums to 1, giving 1 / 4 = 0.25. - [7, 1, -5, 8] sums to 11, giving 11 / 4 = 2.75. - [1, -5, 8, 2] sums to 6, giving 6 / 4 = 1.5.

Example 2

Input:  values = [15, -4, 9], window = 5
Output: []

Only 3 numbers are available, which is fewer than window = 5, so the result is [].

Constraints

  • 0 <= len(values) <= 10^7
  • 1 <= window <= 10^7
  • -2^63 <= values[i] <= 2^63 - 1 for every element in values
  • Return [] whenever len(values) < window
  • window == 1 produces [float(x) for x in values]; window == len(values) produces a single-element list

Step-by-step walkthrough

  1. Restate the problem and output shape

    Given a list values of signed 64-bit integers and a positive window size window >= 1, we must return a list of 64-bit floating-point averages (float), one for every complete contiguous subarray of length window:

    • Too few elements (len(values) < window): No complete window exists, so return [].
    • Enough elements (len(values) >= window): Let num_values = len(values). The first window starts at index 0 (values[0 : window]) and the last window starts at index num_values - window (values[num_values - window : num_values]), giving num_values - window + 1 means in total.

    For Example 1 (num_values = 7, window = 4), we produce 7 - 4 + 1 = 4 means. Each step after the first window must update in O(1) time so the full scan runs in O(n) time.

  2. Why summing every window from scratch is too slow

    The direct approach slices out each window of length window and sums all of its elements from scratch:

    def rolling_means_brute(values: List[int], window: int) -> List[float]:
        means = []
        for start in range(len(values) - window + 1):
            means.append(sum(values[start : start + window]) / window)
        return means
    

    Each window performs window additions, so across num_values - window + 1 windows it does (num_values - window + 1) * window additions. When num_values = 10^7 and window = 5 * 10^6, that is roughly 2.5 * 10^13 additions — hours of work! It is slow because consecutive windows re-add the exact same window - 1 middle elements over and over.

  3. Key idea: slide a running sum in O(1) per step

    Line up two neighboring windows side by side (say window = 3):

    Previous window (ends at right - 1):  [ values[right - 3],  values[right - 2],  values[right - 1] ]
    Current  window (ends at right):                          [ values[right - 2],  values[right - 1],  values[right] ]
                                                    ^                                                        ^
                                              leaves window                                            enters window
    

    All window - 1 middle numbers stay right where they are! Only two boundary elements change when the right edge advances to index right:

    • values[right] enters on the right (add it).
    • values[right - window] leaves on the left (subtract it).

    So after summing the first window elements once (O(window) time), every subsequent window sum takes one addition and one subtraction (O(1) time):

    window_sum = window_sum + values[right] - values[right - window]
    
  4. Keep the running sum as an exact integer, not a float

    Each input x can be as large as 2^63 - 1 (or as negative as -2^63), and window can be 10^7, so the true sum of a window can reach roughly 10^7 * 2^63 ≈ 2^86. That creates two traps in careless implementations:

    1. Fixed-width 64-bit integer overflow (in C++ / Java / Rust): Adding just two copies of 2^63 - 1 overflows a signed 64-bit int64_t.
    2. Permanent floating-point rounding drift: A 64-bit float only stores 53 bits of significant digits. Watch what happens if you accumulate window_sum as a float on values = [2**62, 1, 1] with window = 2:
    Float running sum (BROKEN):
      Window 0 [2**62, 1]:  float(2**62) + 1.0  -> rounds to 4611686018427387904.0 (the +1 is lost!)
      Window 1 [1, 1]:      + 1.0 - float(2**62) -> 1.0 -> mean = 0.5  (WRONG! True mean of [1, 1] is 1.0!)
    
    Exact Python int running sum (CORRECT):
      Window 0 [2**62, 1]:  2**62 + 1 = 4611686018427387905 (exact!)
      Window 1 [1, 1]:      + 1 - 2**62 = 2 -> 2 / 2 = 1.0  (EXACT!)
    

    Python's built-in int has arbitrary precision (it never overflows and never drops low-order bits), and since |window_sum| < 2^87 fits in just three 30-bit CPython digits, every +, -, and / still runs in O(1) time! Dividing window_sum / window only when appending to means converts to a 64-bit float once per window with zero accumulated drift.

  5. Walk through Example 1 step by step

    Trace values = [4, -2, 7, 1, -5, 8, 2] with window = 4:

    Step            | Enters   | Leaves | window_sum             | Mean (window_sum / 4)
    ----------------+----------+--------+------------------------+----------------------
    Initial [0..3]  | 4,-2,7,1 |   --   | 4 + (-2) + 7 + 1 = 10  | 10 / 4 = 2.5
    right = 4       |    -5    |    4   | 10 + (-5) - 4    =  1  |  1 / 4 = 0.25
    right = 5       |     8    |   -2   | 1 + 8 - (-2)     = 11  | 11 / 4 = 2.75
    right = 6       |     2    |    7   | 11 + 2 - 7       =  6  |  6 / 4 = 1.5
    

    For Example 2 (values = [15, -4, 9], window = 5), num_values = 3 < 5, so the guard returns [] right away.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def rolling_means(values: List[int], window: int) -> List[float]:
        num_values = len(values)
    
        # Guard: if fewer elements exist than `window`, zero complete windows can form.
        if num_values < window:
            return []
    
        # Phase 1: Sum the initial complete window values[0 : window].
        # Keep `window_sum` as an exact Python int (arbitrary precision) rather than a float
        # so 64-bit extremes never overflow and rounding error never accumulates across steps.
        window_sum = 0
        for i in range(window):
            window_sum += values[i]
    
        # Store each window's 64-bit float average; `/` always produces a float in Python 3.
        means: List[float] = [window_sum / window]
    
        # Phase 2: Slide the window right one element at a time in O(1) per step.
        # At index `right`, `values[right]` enters on the right and `values[right - window]` leaves on the left.
        for right in range(window, num_values):
            entering_val = values[right]
            leaving_val = values[right - window]
            window_sum += entering_val - leaving_val
            means.append(window_sum / window)
    
        return means
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tracking the average weight of cars currently crossing a 3-car bridge as traffic inches forward one car at a time. Instead of halting traffic to re-weigh all 3 cars from scratch after every move, you weigh the first 3 cars once, and from then on whenever 1 new car rolls onto the front of the bridge and 1 old car rolls off the back, you just add the entering car's weight and subtract the leaving car's weight. This pattern is a fixed-size sliding window (maintaining a running summary over window consecutive items by updating only the entering and leaving boundary items at each step).

Why do naive implementations fail at scale or on extreme inputs? Re-summing values[start : start + window] at every index does O(n * window) additions — up to 2.5 * 10^13 operations when n = 10^7 and window = 5 * 10^6. Updating a floating-point running sum (float_sum += enter - leave) runs in O(n) time, but because a 64-bit float only holds 53 bits of precision, adding 1 to 2^62 silently drops the 1, and that rounding error stays permanently trapped inside float_sum even after 2^62 leaves the window! Keeping window_sum as an exact arbitrary-precision Python int and dividing window_sum / window only when emitting each output gives O(1) exact updates and zero drift.

Here is a trace on Example 1 (values = [4, -2, 7, 1, -5, 8, 2] with window = 4):

Initial window [4, -2, 7, 1]   -> window_sum = 4 + (-2) + 7 + 1 = 10 -> mean = 10 / 4 = 2.5
right = 4 (enter -5, leave  4) -> window_sum = 10 + (-5) - 4    =  1 -> mean =  1 / 4 = 0.25
right = 5 (enter  8, leave -2) -> window_sum = 1 + 8 - (-2)     = 11 -> mean = 11 / 4 = 2.75
right = 6 (enter  2, leave  7) -> window_sum = 11 + 2 - 7       =  6 -> mean =  6 / 4 = 1.5

Complexity

  • Time: O(n) where n = len(values). Summing the first window performs window integer additions, and sliding across the remaining n - window indices performs 1 addition, 1 subtraction, and 1 division per index. Because |values[i]| <= 2^63 and window <= 10^7, |window_sum| never exceeds 10^7 * 2^63 < 2^87 (at most three 30-bit machine limbs in Python), so every arithmetic step takes O(1) time.
  • Space: O(1) auxiliary space (excluding the required output list of max(0, n - window + 1) floats). We store only scalar integers (num_values, window_sum, entering_val, leaving_val, and loop index right).

Edge cases

  • len(values) < window (including values = []): Returns [] immediately before indexing into values.
  • window == 1: The first loop adds values[0] and the second loop swaps one element per step, returning [float(x) for x in values] (note / ensures 4 / 1 is 4.0, a float, not int 4).
  • window == len(values): range(window, num_values) is empty, returning a single-element list [sum(values) / window].
  • Sums exceeding signed 64-bit limits: Three copies of 2^63 - 1 sum to 3 * 2^63 - 3, which overflows C++/Java int64_t (max = 2^63 - 1). Python int stays exact automatically; in C++ use __int128, and in Java/Rust use a 128-bit accumulator (BigInteger or i128).
  • Opposite-sign 64-bit extremes ([-2^63, 2^63 - 1]): The exact integer sum is -1, giving exact mean -0.5 (whereas converting to float first rounds 2^63 - 1 up to 2^63 and wrongly gives 0.0).
  • Invalid window <= 0 in production: Guaranteed >= 1 by the problem constraints, though production code should raise ValueError("window must be >= 1") up front to prevent ZeroDivisionError or negative slice bugs.

Common mistakes

  • Re-summing every window slice (sum(values[i : i + window])): Turns an O(n) scan into O(n * window) quadratic time on large windows.
  • Maintaining window_sum or mean in floating point (mean += (enter - leave) / window): Accumulates rounding error and catastrophic cancellation (severe precision loss when subtracting two huge, rounded floating-point numbers whose leading digits cancel out), leaving stale errors long after an outlier exits the window.
  • Using numpy.cumsum carelessly on 64-bit integers: np.cumsum with dtype=np.int64 silently wraps around modulo 2^64 on overflow (breaking whenever a single window's true sum exceeds int64), while dtype=np.float64 rounds growing prefix sums so subtracting two huge prefix sums wipes out small window averages.
  • Off-by-one output length: Returning n - window or n elements instead of n - window + 1.
  • Returning ints when window == 1: Returning list(values) directly produces int elements instead of 64-bit float elements.

Follow-up questions

  • How would you structure a stateful MovingAverage class with a push(x: int) -> Optional[float] method when observations arrive one at a time from an unbounded live feed? Because the full sequence is no longer stored in RAM, retain only the latest window integers inside a deque (a double-ended queue supporting O(1) append on the right and O(1) pop on the left) — or a pre-allocated fixed-size ring buffer (a circular array of length window indexed by step % window to avoid heap allocations in low-latency systems) — alongside the exact integer window_sum. Each push(x) appends x, subtracts the oldest element once the buffer exceeds window, returns None while warming up (len < window), and otherwise returns window_sum / window in O(1) time and O(window) memory:
from collections import deque
from typing import Optional


class MovingAverage:
    def __init__(self, window: int) -> None:
        if window < 1:
            raise ValueError("window must be >= 1")
        self.window = window
        # buffer: deque holding at most the last `window` ints in arrival order
        self.buffer = deque()
        self.window_sum = 0

    def push(self, x: int) -> Optional[float]:
        self.buffer.append(x)
        self.window_sum += x
        if len(self.buffer) > self.window:
            oldest = self.buffer.popleft()
            self.window_sum -= oldest
        if len(self.buffer) < self.window:
            return None
        return self.window_sum / self.window
  • Suppose the incoming stream contains arbitrary float values rather than integers; how can you stop rounding errors from compounding across millions of window shifts? Whenever raw measurements can be scaled into integer ticks (fixed-point arithmetic), accumulate exact integers (int in Python, __int128 in C++) so drift is literally zero. If inputs are genuinely arbitrary floats, combine Kahan compensated summation (keeping a companion compensation float that captures the tiny low-order rounding error dropped on each + / -) with periodic exact resets: every window arrivals, recompute window_sum = math.fsum(buffer) from scratch in O(window) time, which adds only O(window) / window = O(1) amortized work per arrival (or maintain two alternating accumulators staggered by window // 2 for strict worst-case O(1) latency per step) and guarantees errors never compound indefinitely.
  • What extra state is needed to report the sliding-window variance or standard deviation in O(1) time per arrival? For integer inputs in Python, maintain both exact integer sums S1 = sum(x) and S2 = sum(x * x) as elements enter and leave (S2 += enter * enter - leave * leave), then compute population variance as (window * S2 - S1 * S1) / (window * window) (or divide by window * (window - 1) for sample variance when window >= 2) and take math.sqrt: the integer numerator window * S2 - S1 * S1 is 100% exact and guaranteed >= 0! For floating-point streams where S2 / w - (S1 / w)^2 suffers catastrophic cancellation, use the sliding Welford's online algorithm (an incremental update tracking mean and M2 = sum((x - mean)^2) directly from centered differences), clamping max(0.0, M2) before math.sqrt and periodically resetting every window steps:
mean_new = mean_old + (enter - leave) / window
M2_new   = M2_old + (enter - leave) * (enter - mean_new + leave - mean_old)
variance = M2_new / window

Follow-up questions

Similar questions

More Jump Trading interview questions

All 12 Jump Trading questions →