Sliding Window Average over an Integer Sequence
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests whether a candidate can compute consecutive fixed-width window averages in O(n) time by maintaining a running sum instead of recomputing each window from scratch.
Problem
You are given a list of signed integers and a positive integer width. A complete window is any contiguous subarray of exactly width elements. Your task is to return the arithmetic mean of every complete window, in the order the windows appear.
Specifically, implement:
def window_averages(nums: List[int], width: int) -> List[float]:
The first output value is the mean of nums[0 : width], the second is the mean of nums[1 : width+1], and so on. If the list is shorter than width, there are no complete windows and you must return an empty list.
Your implementation must update the running sum in O(1) per step, so the overall time complexity is O(n).
Constraints
0 <= len(nums) <= 10^71 <= width <= 10^7- Each element
xsatisfies-2^63 <= x <= 2^63 - 1 - Return
[]whenlen(nums) < width - Output values are 64-bit floats (
floatin Python) - You may not recompute the full window sum on every step; the sum must be maintained incrementally
Examples
Example 1
Input: window_averages([1, 3, -1, -3, 5, 3, 6, 7], 3)
Output: [1, -0.3333333333333333, 0.3333333333333333, 1.6666666666666667, 4.666666666666667, 5.333333333333333]
Example 2
Input: window_averages([10, 20], 3)
Output: []
Hints
Hint 1
Think about what changes between two adjacent windows: only one element enters and one element leaves. How much work does that actually require?
Hint 2
Compute the sum of the very first window directly, emit its average, then update the sum as the window slides one position at a time. Each update is a single addition and a single subtraction.
Hint 3
Python integers have arbitrary precision, so your running sum stays exact no matter how large it grows. When would that stop being true in a language like C++ or Java, and what would you do about it?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why the naive approach is too slow
Computing sum(nums[i : i+width]) from scratch for every starting index i costs O(width) per window. With both n and width up to 10^7, that is O(n · width) in the worst case — far too slow.
The sliding-window insight
Two adjacent windows share width - 1 elements. Moving one step to the right does exactly two things:
- one new element enters the right end
- one old element falls off the left end
So the new sum equals the old sum plus the incoming value minus the outgoing value. That is one addition and one subtraction — O(1) work per step.
Algorithm
- If
len(nums) < width, no complete window fits. Return[]immediately. - Sum the first
widthelements. Recordtotal / widthas the first output. - For each index
ifromwidthton - 1:total += nums[i] - nums[i - width]- Append
total / widthto the output.
- Return the output list.
Correctness
The loop maintains the invariant that total equals the exact integer sum of the current window before each division. This holds by induction:
- Base case. After step 2,
total = sum(nums[0 : width]). ✓ - Inductive step. If
total = sum(nums[i-width : i])before iterationi, then after the updatetotal = sum(nums[i-width+1 : i+1]), which is the next window. ✓
The loop runs n - width times, so together with the initial window the output contains n - width + 1 values — exactly the number of complete windows.
A note on numeric precision
Python integers have arbitrary precision. The running total is always an exact integer, regardless of how large it gets, so there is no overflow and no accumulated floating-point drift. The division total / width converts to the nearest 64-bit double only once per window, which is the best you can do.
In a statically typed language like C++ or Java, summing up to 10^7 values near ±2^63 can easily exceed the 64-bit signed range (~87 bits needed). The cleanest fix is a 128-bit accumulator (__int128 in GCC/Clang). Keeping the accumulator as a double avoids overflow but introduces rounding error that compounds over time.
Complexity
| Time | O(n) — O(width) for the seed sum, O(n - width) for the slide |
| Space | O(n - width + 1) for the output; O(1) auxiliary beyond that |
The output size is unavoidable since the problem asks you to return all averages.
Edge cases
| Situation | Result |
|---|---|
nums is empty | 0 < width, so return [] |
len(nums) < width | Return [] |
width == 1 | Every element becomes float(x); the loop runs n - 1 times |
width == len(nums) | The loop body never executes; return a single-element list |
| Large negative values | Python handles them exactly; no special treatment needed |
Reference solution
from typing import List
def window_averages(nums: List[int], width: int) -> List[float]:
n = len(nums)
if n < width:
return []
# Seed the running total with the first complete window.
total = sum(nums[:width])
result = [total / width]
# Slide one step at a time: add the incoming element, drop the outgoing one.
for i in range(width, n):
total += nums[i] - nums[i - width]
result.append(total / width)
return result