2
\$\begingroup\$

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?

asked Sep 22, 2023 at 19:14
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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.

answered Sep 22, 2023 at 21:03
\$\endgroup\$
2
  • 1
    \$\begingroup\$ For those who are wondering, like me, what "LGTM" means: "Looks Good To Me". \$\endgroup\$ Commented 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 be k. \$\endgroup\$ Commented Sep 29, 2023 at 17:00
0
\$\begingroup\$

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));

answered Sep 29, 2023 at 9:51
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.