656. K Radius Subarray Averages
For an index i of a 0-indexed integer array nums, its k-radius average is the average of all elements from nums[i - k] through nums[i + k] inclusive — a window of 2k + 1 elements centered on i. If that window would stick out past either end of the array, the k-radius average is defined as -1.
Write a function that receives nums and the integer k, and returns an array avgs of the same length where avgs[i] is the k-radius average of index i. Averages use integer division truncated toward zero (all elements are non-negative, so this is a plain floor divide of the window sum by 2k + 1).
Example 1:
Input: nums = [2, 5, 3, 8, 1, 4, 9], k = 2
Output: [-1, -1, 3, 4, 5, -1, -1]
Explanation: k = 2 means each average covers 5 elements. Indices 0, 1, 5, 6 don't have 2 neighbors on both sides, so they get -1. For i = 2: (2+5+3+8+1) / 5 = 19 / 5 = 3 after truncation. For i = 3: 21 / 5 = 4, and for i = 4: 25 / 5 = 5.
Example 2:
Input: nums = [6], k = 0
Output: [6]
Explanation: With k = 0 the window is just the element itself, so every index averages to its own value.
Constraints:
- 1 ≤ nums.length ≤ 10⁵
- 0 ≤ nums[i] ≤ 10⁵
- 0 ≤ k ≤ 10⁵
- Window sums can exceed 32-bit range — accumulate in 64 bits.
Hints:
Index i has a full window exactly when k <= i <= n - 1 - k. Everything outside that band is -1 immediately.
Recomputing each window's sum from scratch costs O(k) per index. Adjacent windows overlap in all but two elements — slide: add the entering element, subtract the leaving one.
Equivalently, precompute prefix sums; then any window sum is prefix[i + k + 1] - prefix[i - k], an O(1) lookup.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [2, 5, 3, 8, 1, 4, 9], k = 2
Expected output: [-1, -1, 3, 4, 5, -1, -1]