Click4Ai

16.

Medium

Write a function moving_average(arr, k) that computes the simple moving average of an array with a given window size k. For each valid position i, the moving average is the mean of elements from index i to i+k-1.

Example:

Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 3

Output: [2.0, 3.0, 4.0, 5.0, 6.0]

**Explanation:** Window [1,2,3]->2.0, [2,3,4]->3.0, [3,4,5]->4.0, [4,5,6]->5.0, [5,6,7]->6.0

Constraints:

  • 1 <= k <= len(arr)
  • Return a list of floats with length = len(arr) - k + 1
  • Test Cases

    Test Case 1
    Input: [1, 2, 3, 4, 5, 6, 7], 3
    Expected: [2.0, 3.0, 4.0, 5.0, 6.0]
    Test Case 2
    Input: [10, 20, 30, 40], 2
    Expected: [15.0, 25.0, 35.0]
    Test Case 3
    Input: [5, 5, 5, 5], 4
    Expected: [5.0]
    + 2 hidden test cases