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.
Example 1:
Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Explanation: The 4 subarrays are bolded and underlined below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]
Example 2:
Input: nums = [0,0,0,0,0], goal = 0 Output: 15
Constraints:
1 <= nums.length <= 3 * 104nums[i] is either 0 or 1.0 <= goal <= nums.lengthThe prefix sum approach maintains a running sum and stores it in a hash map to efficiently count subarrays with a given sum. By keeping track of the number of times a particular sum has occurred, this method can determine how many subarrays sum to the desired goal by examining previous prefix sums. This solution is highly efficient as it leverages a linear pass through the array.
This solution uses a hash map to store prefix sums. As the array is traversed, the current sum is updated. For each element, it checks if curr_sum - goal exists in the hash map, which indicates a valid subarray sum, and updates the count accordingly.
JavaScript
Time Complexity: O(N) where N is the length of the array.
Space Complexity: O(N) for storing prefix sums.
The sliding window technique incrementally builds a window of elements and checks if its sum matches the goal. Upon reaching or exceeding the goal sum, the window is adjusted by moving the left boundary to find more subarrays that might sum to the goal. This approach is useful for fixed-sum searches without repetitive recalculations.
This Java implementation uses two pointers to define a sliding window. It increments the end pointer to expand the window until the sum exceeds the goal, then adjusts by incrementing start. It checks for additional valid subarrays by traversing zeros past start.
C++
Time Complexity: O(N) where N is the length of the array.
Space Complexity: O(1) because no additional data structures are used.
| Approach | Complexity |
|---|---|
| Prefix Sum with Hash Map | Time Complexity: O(N) where N is the length of the array. |
| Sliding Window | Time Complexity: O(N) where N is the length of the array. |
LeetCode was HARD until I Learned these 15 Patterns • Ashish Pratap Singh • 1,002,144 views views
Watch 9 more video solutions →Practice Binary Subarrays With Sum with our built-in code editor and test cases.
Practice on FleetCode