K Radius Subarray Averages - 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). If there are less than k elements before or after the index i, then the k-radius average is -1.

Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.

The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.

For example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.

Input & Output

Example 1 — Basic Case
$ Input: nums = [7,4,3,9,1,8,5,2,6], k = 3
Output: [-1,-1,-1,5,-1,-1,-1,-1,-1]
💡 Note: Only index 3 has 3 elements on both sides. Window is [7,4,3,9,1,8,5] with sum 37, so average is 37/7 = 5.
Example 2 — Smaller Radius
$ Input: nums = [1,12,-5,-6,50,3], k = 1
Output: [-1,2,0,13,15,-1]
💡 Note: For k=1, window size is 3. Index 1: (1+12-5)/3 = 8/3 = 2. Index 2: (12-5-6)/3 = 1/3 = 0. Index 3: (-5-6+50)/3 = 39/3 = 13. Index 4: (-6+50+3)/3 = 47/3 = 15.
Example 3 — All Invalid
$ Input: nums = [8], k = 100000
Output: [-1]
💡 Note: k=100000 is larger than array length, so no valid windows exist.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • 0 ≤ k ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
K Radius Subarray Averages INPUT nums array (n=9): 7 4 3 9 1 8 5 2 6 0 1 2 3 4 5 6 7 8 k = 3 Window size = 2*k + 1 = 7 i-k to i+k (7 elements) Valid center: i in [k, n-k-1] i in [3, 5] for this case But window [0,6] for i=3 valid i=4,5: window exceeds bounds ALGORITHM STEPS 1 Initialize avgs to -1 avgs = [-1,-1,...,-1] 2 Calculate prefix sum prefix[i] = sum(nums[0..i-1]) 3 Iterate valid centers for i in [k, n-k-1] 4 Compute window avg sum / (2*k+1) For i=3 (only valid): Window: [0, 6] Elements: 7,4,3,9,1,8,5 Sum = 37 Avg = 37 / 7 = 5 avgs[3] = 5 FINAL RESULT Output avgs array: -1 -1 -1 5 -1 -1 -1 -1 -1 0 1 2 3 4 5 6 7 8 [-1,-1,-1,5,-1, -1,-1,-1,-1] Why -1 for most? i=0,1,2: Not enough elements before i=3: OK - window [0,6] i=4,5,6,7,8: Not enough elements after Only i=3 is valid! Key Insight: Use prefix sum for O(1) range sum queries. Only indices with full k-radius window get computed; others remain -1. Time: O(n), Space: O(n). Sliding window avoids recalculating overlapping sums. TutorialsPoint - K Radius Subarray Averages | Optimal Solution (Prefix Sum)
Asked in
Meta 25 Amazon 18 Google 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen