930. Binary Subarrays With Sum
Explanation:
To solve this problem, we can use the sliding window technique. We iterate through the binary array nums
, maintaining a sliding window that keeps track of the sum of elements within the window. At each step, we check if the sum of elements from the start of the window to the current element equals the given goal
. If it does, we increment the count of subarrays by 1.
Here are the detailed steps:
- Initialize variables
count
andsum
to keep track of the count of subarrays and the running sum respectively. - Initialize a hashmap
sumCount
to store the frequency of each running sum encountered while iterating through the array. - Iterate through the array, adding each element to the running sum.
- For each sum encountered, check if there exists a
requiredSum
such thatsum - requiredSum = goal
. If such arequiredSum
is found, increment the count by the frequency ofrequiredSum
from thesumCount
hashmap. - Increment the frequency of the current
sum
in thesumCount
hashmap. - Return the final count as the answer.
The time complexity of this approach is O(n) where n is the length of the input array nums
, and the space complexity is O(n) as well since we use a hashmap to store the frequency of running sums.
:
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int count = 0, sum = 0;
Map<Integer, Integer> sumCount = new HashMap<>();
sumCount.put(0, 1);
for (int num : nums) {
sum += num;
int requiredSum = sum - goal;
count += sumCount.getOrDefault(requiredSum, 0);
sumCount.put(sum, sumCount.getOrDefault(sum, 0) + 1);
}
return count;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.