KatInterview

Sliding Window Average over an Integer Sequence

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingsliding-windowarraystwo-pointers

Last 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^7
  • 1 <= width <= 10^7
  • Each element x satisfies -2^63 <= x <= 2^63 - 1
  • Return [] when len(nums) < width
  • Output values are 64-bit floats (float in 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?