# Calculating the sum of all k-sized sub-arrays in an array using sliding window algorithm

I need to calculate the sum of all k-sized sub-arrays in an array using sliding window algorithm. Is that a valid sliding window algorithm? If not, why?

var sumOfSubArrays = function(arr, k) {
let currentSubArray = 0;
for(let i=0; i<k; i++) {
currentSubArray += arr[i];
}

let sum = currentSubArray;
for(let i=0; i<arr.length-k; i++) {
current = currentSubArray - arr[i] + arr[i+k];
sum += current;
currentSubArray = current;
}

return sum;
};

let arr = [1,2,3,4,5]
let k = 3;

console.log(sumOfSubArrays(arr, k));


Additionally, what could I improve in this code?

Generally, LGTM. That said,

• It unclear what should happen if k > arr,length. In any case, better test it before entering the first loop.

• If the sliding window is a requirement, I don't see how it could be improved. Otherwise, if k is much smaller than arr.length there is a marginally faster approach. Most of the elements, namely from k to n - k, contribute exactly k times. Compute their sum, multiply it by n - 2*k, and deal with the lead-in and lead-out separately.

• Give your operator some breathing space. i < arr.length - k is more readable than i<arr.length-k.

• For those who are wondering, like me, what "LGTM" means: "Looks Good To Me". Commented Sep 23, 2023 at 8:44
• With most elements contributing exactly k times, why multiply with n - 2*k? That's their number, the weight should be k. Commented Sep 29, 2023 at 17:00

A short review;

• You use var for the function, I would use const, actually I would just use function ;)
• I would use a n inline function that can process a window, otherwise it's hard to tell that you implemented a sliding window
• I would avoid the word array in variable names, unless they are an array
• You never declare current, making it a global

Counter-proposal;

function sumSubArrays(list, k){

const sumWindow = (list) => list.reduce((a, b) => a + b, 0);

let sum = 0;
for(let i = 0; i <= list.length-k; i++){
sum += sumWindow( list.slice(i, i + k) );
}
return sum;
}

let arr = [1,2,3,4,5]
let k = 3;

console.log(27, 27 === sumSubArrays(arr, k));