![]() |
VOOZH | about |
Given an array arr[] of N positive integers, your task is to count the number of subarrays having sum X.
Examples:
Input: N = 5, X = 7, arr[] = {2, 4, 1, 2, 7}
Output: 3
Explanation: There are 3 subarrays with sum = 7.
- Subarray {2, 4, 1}, sum = 2 + 4 + 1 = 7.
- Subarray {4, 1, 2}, sum = 4 + 1 + 2 = 7.
- Subarray {7}, sum = 7.
Input: N = 6, X = 5, arr[] = {1, 1, 1, 1, 1, 1}
Output: 2
Explanation: There are 2 subarrays with sum = 5.
- Subarray {1, 1, 1, 1, 1}, sum = 1 + 1 + 1 + 1 + 1 = 5.
- Subarray {1, 1, 1, 1, 1}, sum = 1 + 1 + 1 + 1 + 1 = 5.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Sliding Window Technique. We can use two pointers: start and end to mark the start and end of the sliding window and also maintain the sum of all the elements from start to end. Initially, we set the start and the end to the first element of the array denoting that there is only the first element in the subarray. Now, we increment end pointer till the sum of the window < X. If at any point the sum of the window = X, then we increment the answer by 1 and move start by 1. Otherwise, if at any point the sum of the window > X, then we keep moving start to decrease window sum till it becomes less than or equal to X. If the sum again becomes = X, then increment answer and move start by 1.
At any point, we keep on expanding the sliding window till sum < X and keep on shrinking the window till sum > X.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(1)