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?
2 Answers 2
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 thanarr.length
there is a marginally faster approach. Most of the elements, namely fromk
ton - k
, contribute exactlyk
times. Compute their sum, multiply it byn - 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 thani<arr.length-k
.
-
1\$\begingroup\$ For those who are wondering, like me, what "LGTM" means: "Looks Good To Me". \$\endgroup\$KIKO Software– KIKO Software2023年09月23日 08:44:05 +00:00Commented Sep 23, 2023 at 8:44
-
\$\begingroup\$ With most elements contributing exactly k times, why multiply with
n - 2*k
? That's their number, the weight should bek
. \$\endgroup\$greybeard– greybeard2023年09月29日 17:00:11 +00:00Commented Sep 29, 2023 at 17:00
A short review;
- You use
var
for the function, I would useconst
, actually I would just usefunction
;) - 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));