Given an array** arr[]** of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it.
Examples:
Input: N = 3, arr[] = {1, 0, 2}
Output:_ 3_
Explanation:
Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.
_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _
1) {1}, sum = 1, length = 1.
2) {0, 2}, sum = 2, length = 2.
3) {1, 0, 2}, sum = 3, length = 3.
Input:_ N = 3, arr[] = {1, 1, 0}_
Output:_ 3_
Explanation:
Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.
_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _
1) {1}, sum = 1, length = 1.
2) {1}, sum = 1, length = 1.
3) {1, 1}, sum = 2, length = 2.
Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays.
_Time Complexity: _O(N2)
Auxiliary Space:_ O(N)_
**Efficient Approach: **This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:
Below is the implementation of the above approach:
// C++ program for the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function that counts the subarrays
// with sum of its elements as its length
**int**
countOfSubarray(``**int**
arr[],
**int**
N)
{
// Decrementing all the elements
// of the array by 1
**for**
(``**int**
i = 0; i < N; i++)
arr[i]--;
// Making prefix sum array
**int**
pref[N];
pref[0] = arr[0];
**for**
(``**int**
i = 1; i < N; i++)
pref[i] = pref[i - 1] + arr[i];
// Declare map to store count of
// elements upto current element
map<``**int**``,
**int**``> mp;
**int**
answer = 0;
// To count all the subarrays
// whose prefix sum is 0
mp[0]++;
// Iterate the array
**for**
(``**int**
i = 0; i < N; i++) {
// Increment answer by count of
// current element of prefix array
answer += mp[pref[i]];
mp[pref[i]]++;
}
// Return the answer
**return**
answer;
}
// Driver Code
**int**
main()
{
// Given array arr[]
**int**
arr[] = { 1, 1, 0 };
**int**
N =
**sizeof**
arr /
**sizeof**
arr[0];
// Function call
cout << countOfSubarray(arr, N);
**return**
0;
}
Output:
3
Time Complexity:_ O(N * Log(N))_
Auxiliary Space:_ O(N)_
#arrays #competitive programming #dynamic programming #greedy #mathematical #cpp-map #subarray #subarray-sum