![]() |
VOOZH | about |
Given a binary array arr[] and an integer k, find the count of non-empty subarrays with a sum equal to k.
Input: arr[] = {1, 0, 1, 1, 0, 1}, k = 2
Output: 6
Explanation: All valid subarrays are: {1, 0, 1}, {0, 1, 1}, {1, 1}, {1, 0, 1}, {0, 1, 1, 0}, {1, 1, 0}.Input: arr[] = {0, 0, 0, 0, 0}, k = 0
Output: 15
Explanation: All subarrays have a sum equal to 0, and there are a total of 15 subarrays.
Table of Content
Consider each subarray in the array and check if the sum is equal to the target.
6
- Use a sliding window with two pointers to count subarrays with sum ≤ k and ≤ k-1.
- Expand the window to the right while the sum stays within the target limit.
- For each position, the number of valid subarrays equals the distance between the two pointers.
- The final answer is count(≤ k) − count(≤ k−1), which gives subarrays with sum exactly k.
6