Back to Sliding Window
Sliding Window
Medium

K Radius Subarray Averages

LAB

For each index, return the integer average of the subarray centered there with radius k, or -1 when the full window does not fit.

EXAMPLES

Example 1
Input
{
  "nums": [
    7,
    4,
    3,
    9,
    1,
    8,
    5,
    2,
    6
  ],
  "k": 3
}

Output
[
  -1,
  -1,
  -1,
  5,
  4,
  4,
  -1,
  -1,
  -1
]

FUNCTION SHAPE

nums: intArrayk: intintArray
SOLUTION NOTE

Note: k in this case refers to one side of the array, so the window is of size 2k+1. We want to update index i-k in res, because that's the midpoint index of the window.

Reveal reference solution +
pythonREFERENCE
def getAverages(self, nums: List[int], k: int) -> List[int]:
    n = len(nums)
    res = [-1] * n
    sum_ = 0

    for i in range(n):
        sum_ += nums[i]

        if i >= 2 * k:
            res[i - k] = sum_ // (2 * k + 1)
            sum_ -= nums[i - 2 * k]

    return res
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.