![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to count the number of subarrays having sum X.
Examples:
Input: N = 5, X = 7, arr[] = {2, -1, 3, 5, -2}
Output: 2
Explanation: There are 2 subarrays with sum = 7.
- Subarray {-1, 3, 5}, sum = -1 + 3 + 5 = 7.
- Subarray {2, -1, 3, 5, 2}, sum = 2 - 1 + 3 + 5 + 2 = 7.
Input: N = 5, X = 3, arr[] = {1, 1, 1, -1, 1}
Output: 2
Explanation: There are 2 subarrays with sum = 3.
- Subarray {1, 1, 1}, sum = 1 + 1 + 1 = 3.
- Subarray {1, 1, 1, -1, 1}, sum = 1 + 1 + 1 - 1 + 1 = 3.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Prefix Sums and Map. We can maintain a Map, that stores the prefix sums along with the number of times they have occurred. At each index i, let's say the prefix sum is P, that is sum of subarray arr[0...i] = P. Now if there is an index j (j < i) such that sum of arr[0...j] = P - X, then the sum of subarray arr[j+1...i] will be equal to X. Therefore, for every index i, if we can find the count of prefixes before i which have sum = P - X, we can add the count to our answer and the sum of count for all indices will be the final answer.
This allows us to find a subarray within our current array (by removing a prefix from our current prefix) that sums up to X. Also, as we iterate through the array, we continuously update the map with the new prefix sum after each step so that all possible prefix sums are counted in the map as we traverse the array.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2
Time Complexity: O(N * logN), where N is the size of array arr[].
Auxiliary Space: O(N)