- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Binary Subarrays With Sum in C++
- Triplet with desired sum in JavaScript
- JavaScript Total subarrays with Sum K
- Finding n subarrays with equal sum in JavaScript
- Subarrays product sum in JavaScript
- Largest sum of subarrays in JavaScript
- Count subarrays with Prime sum in C++
- Finding desired sum of elements in an array in JavaScript
- Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)
- Sum of All Possible Odd Length Subarrays in JavaScript
- Print all subarrays with 0 sum in C++
- Find number of subarrays with even sum in C++
- Check if string ends with desired character in JavaScript
- Generating desired combinations in JavaScript
- Merging subarrays in JavaScript

Advertisements