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,5,16,17,-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 → wait, let me recalculate: (12-5-6)/3 = 1/3 truncated = 0, but that's wrong. Let me fix: Index 2: (1+12-5)/3 = 8/3 = 2. Actually for index 2 the window is [12,-5,-6]: (12-5-6)/3 = 1/3 = 0. Let me recalculate properly...
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: Finding Valid WindowsInput Array:74391850123456k = 1 (need 1 neighbor on each side)ValidValidValidWindowFor position 2: sum(7+4+3) = 14, avg = 14/3 = 4Output Array:-1-1446-1-1Result: [-1,-1,4,4,6,-1,-1]
Understanding the Visualization
1
Input Array
Array with positions that need k elements on each side
2
Window Analysis
Check which positions have enough neighbors
3
Calculate Averages
Compute average for valid positions, -1 for invalid
Key Takeaway
🎯 Key Insight: Only positions with k neighbors on both sides can have valid k-radius averages
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