Neural Mastery
← Practice
Streaming Sliding Window Meanmedium

Streaming Sliding Window Mean

medium Python for AI 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Implement an O(n) moving average window filter by maintaining incremental running sums.

Related Skills

Task

Implement sliding_window_average(nums, k): calculate the moving average for each continuous sub-array of length k across nums. Each mean must be rounded to 4 decimal places. If len(nums) < k or k <= 0, return [].

Function Signature

sliding_window_average(nums: list[float], k: int) -> list[float]

Examples

Example 1: Standard Array
Input: nums = [1, 3, 2, 6, -1, 4, 1, 8, 2] k = 5
Output: [2.2, 2.8, 2.4, 3.6, 2.8]
Example 2: Window Size 1
Input: nums = [10, 20, 30] k = 1
Output: [10, 20, 30]
Example 3: Window Larger Than Array
Input: nums = [1, 2] k = 3
Output: []

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must run in O(n) time using sliding window sum (not recomputing sum(window) at each step).
  • Output values rounded to 4 decimal places.
Python3Saved ✓
def sliding_window_average(nums: list[float], k: int) -> list[float]:
"""Compute sliding window moving averages of width k over nums.
Return each window mean rounded to 4 decimal places. If len(nums) < k or k <= 0, return []."""
# Your implementation here
pass

Case 1: Standard Array
Input: nums = [1, 3, 2, 6, -1, 4, 1, 8, 2] k = 5
Expected: [2.2, 2.8, 2.4, 3.6, 2.8]
Case 2: Window Size 1
Input: nums = [10, 20, 30] k = 1
Expected: [10, 20, 30]
Case 3: Window Larger Than Array
Input: nums = [1, 2] k = 3
Expected: []