K Radius Subarray Averages - Problem
You're given an array of integers and need to calculate the k-radius average for each position in the array.
The k-radius average at index i is the average of all elements within a radius of k positions from i. This includes elements from index i-k to i+k (inclusive).
Important rules:
- If there aren't enough elements on either side (less than
kelements before or after indexi), return-1for that position - Use integer division that truncates toward zero
- The window size is always
2*k + 1elements when valid
Example: For array [7,4,3,9,1,8,5,2,6] with k=3, at index 4 (value 1), we average elements from index 1 to 7: (4+3+9+1+8+5+2)/7 = 32/7 = 4
Input & Output
example_1.py — Basic Case
$
Input:
nums = [7,4,3,9,1,8,5,2,6], k = 3
›
Output:
[-1,-1,-1,5,4,4,-1,-1,-1]
💡 Note:
For k=3, we need 7 elements (2*3+1) in each window. Only indices 3,4,5 have valid windows. Index 3: avg([7,4,3,9,1,8,5]) = 37/7 = 5. Index 4: avg([4,3,9,1,8,5,2]) = 32/7 = 4. Index 5: avg([3,9,1,8,5,2,6]) = 34/7 = 4.
example_2.py — Small K
$
Input:
nums = [100000], k = 0
›
Output:
[100000]
💡 Note:
When k=0, the window size is 1, so each element is its own average. The only element 100000 has average 100000/1 = 100000.
example_3.py — K Too Large
$
Input:
nums = [8], k = 100000
›
Output:
[-1]
💡 Note:
k=100000 requires a window of size 200001, but we only have 1 element. No valid windows exist, so return [-1].
Visualization
Tap to expand
Understanding the Visualization
1
Setup Sensors
Place temperature sensors along a highway with readings at each position
2
Initial Window
Calculate average for first valid k-radius window around a station
3
Slide Window
Move to next station: drop leftmost reading, add new rightmost reading
4
Update Average
Compute new average using updated sum, avoiding recalculation
Key Takeaway
🎯 Key Insight: The sliding window technique transforms an O(n×k) problem into O(n) by reusing overlapping calculations instead of starting from scratch each time.
Time & Space Complexity
Time Complexity
O(n)
Single pass through array, each element added and removed exactly once
✓ Linear Growth
Space Complexity
O(1)
Only storing window sum and a few variables besides output array
✓ Linear Space
Constraints
- n == nums.length
- 1 ≤ n ≤ 105
- 0 ≤ nums[i], k ≤ 105
- Important: Use integer division that truncates toward zero
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code