K Radius Subarray Averages — LeetCode 2090 Python Solution

MediumArraySliding Window
Problem
#2090
Reading time
3 min

The problem

You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive).

Example

Input
nums = [7,4,3,9,1,8,5,2,6], k = 3
Output
[-1,-1,-1,5,4,4,-1,-1,-1]
Explanation
- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.

Python solution

Python
class Solution:
    def getAverages(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        ans = [-1] * n
        s = 0
        for i, x in enumerate(nums):
            s += x
            if i >= k * 2:
                ans[i - k] = s // (k * 2 + 1)
                s -= nums[i - k * 2]
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2090. K Radius Subarray Averages is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2090. K Radius Subarray Averages?
LeetCode 2090. K Radius Subarray Averages is rated Medium on LeetCode.
What is the time complexity of LeetCode 2090. K Radius Subarray Averages?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 2090. K Radius Subarray Averages?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2090. K Radius Subarray Averages cover?
LeetCode 2090. K Radius Subarray Averages is tagged Array and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview