Leetcode 930: Binary Subarrays With Sum

grid47
grid47
Exploring patterns and algorithms
Aug 6, 2024 6 min read

You are given a binary array nums and an integer goal. Your task is to return the number of non-empty contiguous subarrays that have a sum equal to the given goal. A subarray is defined as any contiguous part of the array.
Problem
Approach
Steps
Complexity
Input: You are given a binary array nums, consisting of 0's and 1's, and an integer goal. You need to find the number of subarrays that sum up to the goal.
Example: Input: nums = [1,1,0,1,0,1], goal = 2
Constraints:
• 1 <= nums.length <= 3 * 10^4
• nums[i] is either 0 or 1.
• 0 <= goal <= nums.length
Output: Return the total number of non-empty subarrays whose sum equals the given goal.
Example: Output: 4
Constraints:
• The array will not be empty.
Goal: The objective is to find how many subarrays have a sum equal to the given goal.
Steps:
• 1. Use the sliding window technique to count the number of subarrays whose sum is less than or equal to the goal.
• 2. Calculate the number of subarrays whose sum is at most 'goal' and subtract the result for 'goal-1' from it to get the exact number of subarrays with sum equal to 'goal'.
• 3. Implement the helper function 'atmost' to count subarrays with sum at most a given value, and use it to compute the result.
Goal: The input binary array will consist of 0's and 1's, and the goal will be a non-negative integer not exceeding the length of the array.
Steps:
• 1 <= nums.length <= 3 * 10^4
• nums[i] is either 0 or 1.
• 0 <= goal <= nums.length
Assumptions:
• The input array is always non-empty, and its elements are either 0 or 1.
Input: Input: nums = [1,1,0,1,0,1], goal = 2
Explanation: In this case, the following subarrays have a sum of 2: [1,1], [1,1], [0,1,0], and [1,1]. Thus, the output is 4.

Input: Input: nums = [0,0,0,0], goal = 0
Explanation: Here, every subarray has a sum of 0. Therefore, there are 15 such subarrays (which includes all possible non-empty subarrays of the input array).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus