Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Google
Amazon
K Radius Subarray Averages

Compute the average of every subarray centered at each index with radius k, or -1 when the centered window does not fit.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums and an integer k, define the k-radius average at index i as the average of the subarray centered at i with length 2k + 1:

  • the subarray is nums[i-k ... i+k]
  • if that subarray goes out of bounds, the value at i is -1

Return an array averages where averages[i] is the k-radius average of nums centered at index i, using integer division by the window length 2k + 1.

Notes

  • The result at each valid position is the floor of the exact average for non-negative sums, and standard integer division behavior for integer arithmetic in the chosen language.
  • Positions that cannot form a full centered window must be set to -1.

Input Format

  • An integer array nums
  • An integer k

Output Format

  • Return an integer array of the same length as nums.
  • For each index i, output the average of the centered window of size 2k+1 if it exists, otherwise -1.

Constraints

  • 1 <= nums.length
  • 0 <= k
  • A centered window is valid only when i-k >= 0 and i+k < nums.length

Hints

  • A naive solution recomputes the sum for every index and is too slow for large arrays.
  • Precompute prefix sums so each window sum can be answered in constant time.

Input Format

  • nums: integer array
  • k: non-negative integer

Output Format

  • Integer array averages of length nums.length

Constraints

  • Use a centered window of size 2k + 1
  • Return -1 for indices without a full window
  • Compute each valid window average efficiently
Examples
Sample cases returned by the problem API.

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]

Explanation

The centered window has length 7. For index 3, the sum of [7,4,3,9,1,8,5] is 37, and 37 / 7 = 5. Similarly, index 4 gives 31 / 7 = 4, and index 5 gives 28 / 7 = 4. The other positions do not have enough elements on both sides.

Example 2

Input

nums = [100000], k = 0

Output

[100000]

Explanation

A window of length 1 centered at index 0 is valid, so the average is the element itself.

Show 1 more example

Example 3

Input

nums = [8,8,8,8], k = 1

Output

[-1,8,8,-1]

Explanation

Only indices 1 and 2 have a full window of length 3. Each window sums to 24, and 24 / 3 = 8.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.