Binary subarrays with desired sum in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a binary array, arr, as the first argument, and a number, target, as the second argument.

Our function is supposed to count the number of subarrays that exists in the array arr, the sum of whose elements is equal to count. We should finally return this count.

For example, if the input to the function is

Input

const arr = [1, 0, 1, 0, 1];
const target = 2;

Output

const output = 4;

Output Explanation

Because the desired subarrays are:

[1,0,1][1,0,1,0]
[0,1,0,1]
[1,0,1]

Example

 Live Demo

const arr = [1, 0, 1, 0, 1];
const target = 2;
const countSubarrays = (arr = [], target = 1) => {
   const map = {}
   let sum = 0
   let count = 0
   for (const num of arr) {
      map[sum] = (map[sum] || 0) + 1
      sum += num
      count += map[sum - target] || 0
   }
   return count
};
console.log(countSubarrays(arr, target));

Output

4
raja
Published on 23-Apr-2021 10:53:43
Advertisements