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^71 <= window <= 10^7-2^63 <= values[i] <= 2^63 - 1for every element invalues- Return
[]wheneverlen(values) < window window == 1produces[float(x) for x in values];window == len(values)produces a single-element list
Step-by-step walkthrough
Restate the problem and output shape
Given a list
valuesof signed 64-bit integers and a positive window sizewindow >= 1, we must return a list of 64-bit floating-point averages (float), one for every complete contiguous subarray of lengthwindow:- Too few elements (
len(values) < window): No complete window exists, so return[]. - Enough elements (
len(values) >= window): Letnum_values = len(values). The first window starts at index0(values[0 : window]) and the last window starts at indexnum_values - window(values[num_values - window : num_values]), givingnum_values - window + 1means in total.
For Example 1 (
num_values = 7,window = 4), we produce7 - 4 + 1 = 4means. Each step after the first window must update inO(1)time so the full scan runs inO(n)time.- Too few elements (
Why summing every window from scratch is too slow
The direct approach slices out each window of length
windowand 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 meansEach window performs
windowadditions, so acrossnum_values - window + 1windows it does(num_values - window + 1) * windowadditions. Whennum_values = 10^7andwindow = 5 * 10^6, that is roughly2.5 * 10^13additions — hours of work! It is slow because consecutive windows re-add the exact samewindow - 1middle elements over and over.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 windowAll
window - 1middle numbers stay right where they are! Only two boundary elements change when the right edge advances to indexright:values[right]enters on the right (add it).values[right - window]leaves on the left (subtract it).
So after summing the first
windowelements 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]Keep the running sum as an exact integer, not a float
Each input
xcan be as large as2^63 - 1(or as negative as-2^63), andwindowcan be10^7, so the true sum of a window can reach roughly10^7 * 2^63 ≈ 2^86. That creates two traps in careless implementations:- Fixed-width 64-bit integer overflow (in C++ / Java / Rust): Adding just two copies of
2^63 - 1overflows a signed 64-bitint64_t. - Permanent floating-point rounding drift: A 64-bit
floatonly stores53bits of significant digits. Watch what happens if you accumulatewindow_sumas afloatonvalues = [2**62, 1, 1]withwindow = 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
inthas arbitrary precision (it never overflows and never drops low-order bits), and since|window_sum| < 2^87fits in just three 30-bit CPython digits, every+,-, and/still runs inO(1)time! Dividingwindow_sum / windowonly when appending tomeansconverts to a 64-bitfloatonce per window with zero accumulated drift.- Fixed-width 64-bit integer overflow (in C++ / Java / Rust): Adding just two copies of
Walk through Example 1 step by step
Trace
values = [4, -2, 7, 1, -5, 8, 2]withwindow = 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.5For Example 2 (
values = [15, -4, 9], window = 5),num_values = 3 < 5, so the guard returns[]right away.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)wheren = len(values). Summing the first window performswindowinteger additions, and sliding across the remainingn - windowindices performs1addition,1subtraction, and1division per index. Because|values[i]| <= 2^63andwindow <= 10^7,|window_sum|never exceeds10^7 * 2^63 < 2^87(at most three 30-bit machine limbs in Python), so every arithmetic step takesO(1)time. - Space:
O(1)auxiliary space (excluding the required output list ofmax(0, n - window + 1)floats). We store only scalar integers (num_values,window_sum,entering_val,leaving_val, and loop indexright).
Edge cases
len(values) < window(includingvalues = []): Returns[]immediately before indexing intovalues.window == 1: The first loop addsvalues[0]and the second loop swaps one element per step, returning[float(x) for x in values](note/ensures4 / 1is4.0, afloat, notint4).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 - 1sum to3 * 2^63 - 3, which overflows C++/Javaint64_t(max = 2^63 - 1). Pythonintstays exact automatically; in C++ use__int128, and in Java/Rust use a 128-bit accumulator (BigIntegerori128). - Opposite-sign 64-bit extremes (
[-2^63, 2^63 - 1]): The exact integer sum is-1, giving exact mean-0.5(whereas converting tofloatfirst rounds2^63 - 1up to2^63and wrongly gives0.0). - Invalid
window <= 0in production: Guaranteed>= 1by the problem constraints, though production code should raiseValueError("window must be >= 1")up front to preventZeroDivisionErroror negative slice bugs.
Common mistakes
- Re-summing every window slice (
sum(values[i : i + window])): Turns anO(n)scan intoO(n * window)quadratic time on large windows. - Maintaining
window_sumormeanin 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.cumsumcarelessly on 64-bit integers:np.cumsumwithdtype=np.int64silently wraps around modulo2^64on overflow (breaking whenever a single window's true sum exceedsint64), whiledtype=np.float64rounds growing prefix sums so subtracting two huge prefix sums wipes out small window averages. - Off-by-one output length: Returning
n - windowornelements instead ofn - window + 1. - Returning
ints whenwindow == 1: Returninglist(values)directly producesintelements instead of64-bitfloatelements.
Follow-up questions
- How would you structure a stateful
MovingAverageclass with apush(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 latestwindowintegers inside a deque (a double-ended queue supportingO(1)append on the right andO(1)pop on the left) — or a pre-allocated fixed-size ring buffer (a circular array of lengthwindowindexed bystep % windowto avoid heap allocations in low-latency systems) — alongside the exact integerwindow_sum. Eachpush(x)appendsx, subtracts the oldest element once the buffer exceedswindow, returnsNonewhile warming up (len < window), and otherwise returnswindow_sum / windowinO(1)time andO(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
floatvalues 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 (intin Python,__int128in C++) so drift is literally zero. If inputs are genuinely arbitrary floats, combine Kahan compensated summation (keeping a companioncompensationfloat that captures the tiny low-order rounding error dropped on each+/-) with periodic exact resets: everywindowarrivals, recomputewindow_sum = math.fsum(buffer)from scratch inO(window)time, which adds onlyO(window) / window = O(1)amortized work per arrival (or maintain two alternating accumulators staggered bywindow // 2for strict worst-caseO(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 sumsS1 = sum(x)andS2 = 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 bywindow * (window - 1)for sample variance whenwindow >= 2) and takemath.sqrt: the integer numeratorwindow * S2 - S1 * S1is 100% exact and guaranteed>= 0! For floating-point streams whereS2 / w - (S1 / w)^2suffers catastrophic cancellation, use the sliding Welford's online algorithm (an incremental update trackingmeanandM2 = sum((x - mean)^2)directly from centered differences), clampingmax(0.0, M2)beforemath.sqrtand periodically resetting everywindowsteps:
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
- 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?
- Suppose the incoming stream contains arbitrary `float` values rather than integers; how can you stop rounding errors from compounding across millions of window shifts?
- What extra state is needed to report the sliding-window variance or standard deviation in `O(1)` time per arrival?
Similar questions
- Enumerate Serial Paths from a Workflow Grammar
- Internals of C++ vector, unordered_map, and Virtual Dispatch
- Filter Source Files Requiring Replication
- Find Non-Writable Filenames from Permission Strings
- Maximum Subset With Nonzero Bitwise AND
- Rule-Based Share Tracking and Pairwise String Reduction
More Jump Trading interview questions
- Low-Latency Tree Ensemble Inference Hard
- Postfix Macro Evaluation and Lock-Free C++ Primitives Easy
- Columnar Binary Storage Format for Market Data Hard Pro
- Enumerate Serial Paths from a Workflow Grammar Easy Pro
- Internals of C++ vector, unordered_map, and Virtual Dispatch Medium Pro
- Maximum Group Size of Equivalent Ratios Easy Pro
- Filter Source Files Requiring Replication Easy Pro
- Find Non-Writable Filenames from Permission Strings Medium Pro
- Maximum Subset With Nonzero Bitwise AND Easy Pro
- Rule-Based Share Tracking and Pairwise String Reduction Medium Pro