Back to Practice
#0053
Compute Sliding Window Averages
MediumPython18 min15 XP
Problem
Given a list of numbers and an integer k, return a list of averages for every contiguous window of length k. If k is invalid or larger than the list length, return an empty list.
Why This Matters
Sliding windows appear in time-series smoothing, rolling metrics, log analytics, signal processing, and DSA interviews.
Function Signature
def window_averages(values, k):
Examples
Example 1
Inputvalues = [2, 4, 6, 8, 10], k = 3
Output[4.0, 6.0, 8.0]
The windows are [2,4,6], [4,6,8], and [6,8,10].
Constraints
- k may be invalid.
- Values can be integers or floats.
- Use O(n) time.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Three-value windows
Input[2, 4, 6, 8, 10], 3
Expected[4.0, 6.0, 8.0]
Each average reuses most of the previous window.
Window size one
Input[5, -1, 3], 1
Expected[5.0, -1.0, 3.0]
A size-one window average is the value itself as a float.
Hidden Test Categories
k larger than list lengthk equal to list lengthnegative and decimal values