Sliding Window Average

Easy~15 min

Given an array of numbers nums and a window size k, return an array of the averages of each contiguous window of size k.

Round each average to 2 decimal places.

For example, given nums = [1, 3, 2, 6, -1, 4, 1, 8, 2] and k = 5:

  • Window [1, 3, 2, 6, -1] → average = 2.2
  • Window [3, 2, 6, -1, 4] → average = 2.8
  • Window [2, 6, -1, 4, 1] → average = 2.4
  • Window [6, -1, 4, 1, 8] → average = 3.6
  • Window [-1, 4, 1, 8, 2] → average = 2.8

Result: [2.2, 2.8, 2.4, 3.6, 2.8]

Examples

Example 1
Input: nums = [1, 3, 2, 6, -1, 4, 1, 8, 2], k = 5
Output: [2.2, 2.8, 2.4, 3.6, 2.8]
Explanation: Each value is the average of a contiguous window of 5 elements.
Example 2
Input: nums = [4, 4, 4, 4], k = 2
Output: [4.0, 4.0, 4.0]
Explanation: All windows have the same average.
Example 3
Input: nums = [10], k = 1
Output: [10.0]
Explanation: With k=1, each element is its own window.

Constraints

  • 1 <= k <= nums.length <= 10^4
  • -10^6 <= nums[i] <= 10^6
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run