Sponsored
Sponsored
This approach involves iterating over each element in the array and calculating the subarray sum for each index considering the radius. If there is an insufficient number of elements, return -1 for that index. The average is computed using integer division.
Time Complexity: O(n*k), where n is the size of the array.
Space Complexity: O(n), for the output array.
1function getAverages(nums, k) {
2 const n = nums.length;
3 const avgs = Array(n).fill(-1);
4 const subArraySize = 2 * k + 1;
5
6 for (let i = k; i < n - k; i++) {
7 let sum = 0;
8 for (let j = i - k; j <= i + k; j++) {
9 sum += nums[j];
10 }
11 avgs[i] = Math.floor(sum / subArraySize);
12 }
13
14 return avgs;
15}
16
17const nums = [7, 4, 3, 9, 1, 8, 5, 2, 6];
18const k = 3;
19console.log(getAverages(nums, k));
The JavaScript solution also uses a simple double loop to compute and store averages, with handling for insufficient elements using -1 offset.
The sliding window approach helps optimize the brute force method by avoiding redundant calculations when sums overlap, significantly reducing the time complexity.
Time Complexity: O(n), as each element is added and removed from the sum at most once.
Space Complexity: O(n), for storing the results.
1
This JavaScript solution optimizes the average calculation using a sliding window technique, effectively lowering the time complexity while keeping the calculation straightforward.