Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2090: K Radius Subarray Averages

In this guide, we solve Leetcode #2090 K Radius Subarray Averages in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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).

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Sliding Window

Intuition

We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.

Expanding and shrinking the window lets us maintain validity without restarting the scan.

Approach

Grow the window with a right pointer, and shrink from the left only when the constraint is violated.

Track the best window as you go to keep the solution linear.

Steps:

  • Expand the right end of the window.
  • While invalid, move the left end to restore constraints.
  • Update the best window found.

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. - The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37. Using integer division, avg[3] = 37 / 7 = 5. - For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4. - For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4. - avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.

Python Solution

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

The time complexity is O(n)O(n)O(n), where nnn is the length of the array nums\textit{nums}nums. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy