#2090
Medium Algorithms K radius subarray averages
Array Sliding Window
46.1% acceptance
Feb 25, 2026
2087
104
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn get_averages(nums: Vec<i32>, k: i32) -> Vec<i32> {
let n = nums.len();
let k = k as usize;
let window = 2 * k + 1;
let mut avgs = vec![-1i32; n];
if window > n {
return avgs;
}
// Prefix sum
let mut prefix = vec![0i64; n + 1];
for i in 0..n {
prefix[i + 1] = prefix[i] + nums[i] as i64;
}
for i in k..n - k {
let sum = prefix[i + k + 1] - prefix[i - k];
avgs[i] = (sum / window as i64) as i32;
}
avgs
}
}