
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary Subarrays with Desired Sum in JavaScript
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
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
Advertisements