Binary subarrays with desired sum in JavaScript

We need to write a JavaScript function that counts the number of subarrays in a binary array whose elements sum to a target value.

Problem Statement

Given a binary array arr and a target number, count all subarrays where the sum of elements equals the target.

Example Input:

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

Expected Output:

4

Explanation: The subarrays with sum 2 are:

[1, 0, 1] (indices 0-2)
[1, 0, 1] (indices 2-4)  
[0, 1, 0, 1] (indices 1-4)
[1, 0, 1, 0] (indices 0-3)

Solution Using Prefix Sum and HashMap

The optimal approach uses a prefix sum technique with a hash map to track cumulative sums:

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

How It Works

The algorithm uses these key concepts:

  • Prefix Sum: Running total of array elements
  • HashMap: Stores frequency of each prefix sum
  • Key Insight: If prefixSum[j] - prefixSum[i] = target, then subarray from i+1 to j has the desired sum
// Step-by-step trace for [1, 0, 1, 0, 1], target = 2
const traceExample = () => {
    const arr = [1, 0, 1, 0, 1];
    const target = 2;
    const map = {};
    let sum = 0;
    let count = 0;
    
    console.log("Step | Element | Sum | Map | Count");
    console.log("-----|---------|-----|-----|------");
    
    for (let i = 0; i < arr.length; i++) {
        map[sum] = (map[sum] || 0) + 1;
        sum += arr[i];
        const increment = map[sum - target] || 0;
        count += increment;
        
        console.log(`${i+1}    | ${arr[i]}       | ${sum}   | ${JSON.stringify(map)} | ${count}`);
    }
    
    return count;
};

traceExample();
Step | Element | Sum | Map | Count
-----|---------|-----|-----|------
1    | 1       | 1   | {"0":1} | 0
2    | 0       | 1   | {"0":1,"1":1} | 0
3    | 1       | 2   | {"0":1,"1":2} | 1
4    | 0       | 2   | {"0":1,"1":2,"2":1} | 1
5    | 1       | 3   | {"0":1,"1":2,"2":2} | 3
4

Alternative Brute Force Approach

For better understanding, here's a simpler but less efficient O(n²) solution:

const countSubarraysBruteForce = (arr, target) => {
    let count = 0;
    
    for (let i = 0; i < arr.length; i++) {
        let sum = 0;
        for (let j = i; j < arr.length; j++) {
            sum += arr[j];
            if (sum === target) {
                count++;
            }
        }
    }
    
    return count;
};

console.log(countSubarraysBruteForce([1, 0, 1, 0, 1], 2));
4

Comparison

Approach Time Complexity Space Complexity Best For
Prefix Sum + HashMap O(n) O(n) Large arrays
Brute Force O(n²) O(1) Small arrays, learning

Conclusion

The prefix sum approach with HashMap provides an efficient O(n) solution for counting subarrays with a target sum. This technique is valuable for many array sum problems in competitive programming and interviews.

Updated on: 2026-03-15T23:19:00+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements