JavaScript Total subarrays with Sum K

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a single number as the second argument. The function should find and return the count of total number of continuous subarrays whose sum equals to the number specified by the second argument.

It is guaranteed that all the numbers in the array are positive numbers.

For example −

If the inputs are −

const arr = [1, 1, 1];
const sum = 2;

Then the output should be 2 because there are exactly two subarrays in this array that sums to 2.

We will use the sliding window algorithm that uses a two-pointer approach to find the desired windows (subarrays with required sums) and count their number.

Example

const arr = [1, 2, 3, 4, 5];
const sum = 5;
// two pointer approach to find one matching subarray
const findOne = (arr, target, start = 0) => {
   let left = start, right = start, sum = 0;
   while(right < arr.length){
      sum += arr[right];
      if(sum === target){
         return true;
      }
      else if(sum < target){
         right++;
      }else{
         left++;
         sum -= left;
         if(left > right){
            right = left;
         };
      };
   };
   return false;
};
// iterating over the array to find all pair count const findAll = (arr = [], target) => {
   let count = 0;
   for(let i = 0; i < arr.length; i++){
      count += findOne(arr, target, i);
   };
   return count;
};
console.log(findAll(arr, sum));
console.log(findAll([1, 1, 1], 2));

Output

And the output in the console will be −

2
2
raja
Published on 25-Nov-2020 07:46:12
Advertisements