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:
- Decrement all the array elements by 1.
- Initialize a prefix array with prefix[0] = arr[0].
- Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].
- Initialize the answer to 0.
- Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.
- Increment the value of the current element in the map.
- Print the value of answer after the above steps.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOfSubarray( int arr[], int N)
{
for ( int i = 0; i < N; i++)
arr[i]--;
int pref[N];
pref[0] = arr[0];
for ( int i = 1; i < N; i++)
pref[i] = pref[i - 1] + arr[i];
map< int , int > mp;
int answer = 0;
mp[0]++;
for ( int i = 0; i < N; i++) {
answer += mp[pref[i]];
mp[pref[i]]++;
}
return answer;
}
int main()
{
int arr[] = { 1, 1, 0 };
int N = sizeof arr / sizeof arr[0];
cout << countOfSubarray(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countOfSubarray( int arr[], int N)
{
for ( int i = 0 ; i < N; i++)
arr[i]--;
int []pref = new int [N];
pref[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < N; i++)
pref[i] = pref[i - 1 ] + arr[i];
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
int answer = 0 ;
mp.put( 0 , 1 );
for ( int i = 0 ; i < N; i++)
{
if (mp.containsKey(pref[i]))
{
answer += mp.get(pref[i]);
mp.put(pref[i], mp.get(pref[i]) + 1 );
}
else
{
mp.put(pref[i], 1 );
}
}
return answer;
}
public static void main(String[] args)
{
int arr[] = { 1 , 1 , 0 };
int N = arr.length;
System.out.print(countOfSubarray(arr, N));
}
}
|
Python3
from collections import defaultdict
def countOfSubarray(arr, N):
for i in range (N):
arr[i] - = 1
pref = [ 0 ] * N
pref[ 0 ] = arr[ 0 ]
for i in range ( 1 , N):
pref[i] = pref[i - 1 ] + arr[i]
mp = defaultdict( lambda : 0 )
answer = 0
mp[ 0 ] + = 1
for i in range (N):
answer + = mp[pref[i]]
mp[pref[i]] + = 1
return answer
arr = [ 1 , 1 , 0 ]
N = len (arr)
print (countOfSubarray(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countOfSubarray( int []arr, int N)
{
for ( int i = 0; i < N; i++)
arr[i]--;
int []pref = new int [N];
pref[0] = arr[0];
for ( int i = 1; i < N; i++)
pref[i] = pref[i - 1] + arr[i];
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
int answer = 0;
mp.Add(0, 1);
for ( int i = 0; i < N; i++)
{
if (mp.ContainsKey(pref[i]))
{
answer += mp[pref[i]];
mp[pref[i]]= mp[pref[i]] + 1;
}
else
{
mp.Add(pref[i], 1);
}
}
return answer;
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 0 };
int N = arr.Length;
Console.Write(countOfSubarray(arr, N));
}
}
|
Javascript
<script>
function countOfSubarray( arr, N){
for (let i = 0; i < N; i++)
arr[i]--;
let pref = [];
pref[0] = arr[0];
for (let i = 1; i < N; i++)
pref[i] = pref[i - 1] + arr[i];
let mp = new Map;
let answer = 0;
if (mp[0])
mp[0]++;
else
mp[0] = 1;
for (let i = 0; i < N; i++) {
if (mp[pref[i]]){
answer += mp[pref[i]];
mp[pref[i]]++;
}
}
return answer;
}
let arr = [ 1, 1, 0 ];
let N = arr.length;
document.write(countOfSubarray(arr, N));
</script>
|
Time Complexity: O(N * Log(N))
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
18 May, 2021
Like Article
Save Article