Problem Description
Given a 0-indexed integer array nums and an integer k, compute the k-radius average for each index i. The k-radius average is the integer division average of all elements in the subarray spanning indices i - k to i + k (inclusive). If there are fewer than k elements before or after i, the value is set to -1.
Key Insights
- Use a sliding window of size (2k + 1) to efficiently compute subarray sums.
- Only update the window sum by subtracting the element that falls out and adding the new element that enters.
- For positions where a full window cannot be formed (i.e. indices < k or >= n - k), mark the output as -1.
- Handle special case k = 0 by returning the original array.
Space and Time Complexity
Time Complexity: O(n) – Each element is processed at most once during the window slide. Space Complexity: O(n) – Output array storing averages for each element.
Solution
We first create a result array initialized with -1. If k equals 0, we simply return the original array as each average is the element itself. For k > 0, we calculate the initial window sum for the first (2k + 1) elements. Starting at index k, we assign the integer division of this sum to the corresponding average. Then we slide the window one position at a time by subtracting the element that slides out from the left and adding the new element from the right. This approach ensures that we maintain the running sum in O(1) per step and compute all required averages efficiently.