Binary Subarrays With Sum

Binary Subarrays With Sum

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

A subarray is a contiguous part of the array.

LeetCode Problem - 930

import java.util.HashMap;
import java.util.Map;

class Solution {
    // Method to count the number of subarrays with a given sum
    public int numSubarraysWithSum(int[] nums, int goal) {
        int res = 0; // Initialize the result variable
        int ps = 0; // Initialize the prefix sum variable
        Map<Integer, Integer> mp = new HashMap<>(); // Create a map to store prefix sums and their frequencies
        mp.put(0, 1); // Initialize the map with 0 sum having frequency 1

        // Loop through each element of the array
        for(int e : nums){
            ps += e; // Update the prefix sum
            // Update the result by adding the frequency of prefix sum (ps - goal) if present in the map
            res += mp.getOrDefault(ps - goal, 0);
            // Update the frequency of current prefix sum in the map
            mp.put(ps, mp.getOrDefault(ps, 0) + 1);
        }
        // Return the final result
        return res;
    }
}