Count of subarrays having sum equal to its length | Set 2
Last Updated :
25 Aug, 2021
Given an array arr[] of size N, the task is to find the number of subarrays having 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 the 6 subarrays, following three subarrays satisfy the given conditions:
- {1}: Sum = 1, Length = 1
- {0, 2}: Sum = 2, Length = 2
- {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 the 6 subarrays, following three subarrays satisfy the given conditions:
- {1}: Sum = 1, Length = 1
- {1, 1}: Sum = 2, Length = 2
- {1}: Sum = 1, Length = 1
Input: N = 6, arr[] = {1, 1, 1}Output: 3Explanation:Total number of subarrays are 6, i.e. {1}, {1}, {1}, {1, 1}, {1, 1}, {1, 1, 1}.Out of the 6 subarrays, following six subarrays satisfy the given conditions:
- {1},{1},{1}: Sum=1, Length=1 ,Number of Subarrays=3
- {1,1},{1,1}: Sum=2, Length=2, Number of Subarrays=2
- {1,1,1}: Sum=3, Length=3, Number of Subarrays=1
Total Number of subarrays having Sum equals to it’s Length=6
Naive and Prefix Sum based Approach: Refer to previous post for the simplest and prefix sum based approaches to solve the problem.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to store the previous occurrences of subarrays with the given conditions and make use of unordered_map for constant lookup. Below are the steps:
- Initialize an unordered_map M, answer to store the count of subarrays, and sum to store the prefix sum of the array.
- Traverse the given array and do the following:
- Add the current element to the sum.
- If M[sum – i] exists then add this value to the answer as there exists a subarray of length i whose sum of the element is the current sum.
- Increment the frequency of (sum – i) in the map M.
- After the above steps, print the value of the answer as the total count of subarrays.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOfSubarray( int arr[], int N)
{
unordered_map< int , int > mp;
int answer = 0;
int sum = 0;
mp[1]++;
for ( int i = 0; i < N; i++) {
sum += arr[i];
answer += mp[sum - i];
mp[sum - i]++;
}
cout << answer;
}
int main()
{
int arr[] = { 1, 0, 2, 1, 2, -2, 2, 4 };
int N = sizeof arr / sizeof arr[0];
countOfSubarray(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void countOfSubarray( int arr[], int N)
{
Map<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
int answer = 0 ;
int sum = 0 ;
if (mp.get( 1 ) != null )
mp.put( 1 , mp.get( 1 ) + 1 );
else
mp.put( 1 , 1 );
for ( int i = 0 ; i < N; i++)
{
sum += arr[i];
if (mp.get(sum - i) != null )
answer += mp.get(sum - i);
if (mp.get(sum - i) != null )
mp.put(sum - i, mp.get(sum - i) + 1 );
else
mp.put(sum - i, 1 );
}
System.out.print(answer);
}
public static void main(String args[])
{
int arr[] = { 1 , 0 , 2 , 1 , 2 , - 2 , 2 , 4 };
int N = arr.length;
countOfSubarray(arr, N);
}
}
|
Python3
from collections import defaultdict
def countOfSubarray(arr, N):
mp = defaultdict( lambda : 0 )
answer = 0
sum = 0
mp[ 1 ] + = 1
for i in range (N):
sum + = arr[i]
answer + = mp[ sum - i]
mp[ sum - i] + = 1
print (answer)
if __name__ = = '__main__' :
arr = [ 1 , 0 , 2 , 1 , 2 , - 2 , 2 , 4 ]
N = len (arr)
countOfSubarray(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void countOfSubarray( int []arr,
int N)
{
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
int answer = 0;
int sum = 0;
mp[1] = 1;
for ( int i = 0; i < N; i++)
{
sum += arr[i];
if (mp.ContainsKey(sum - i))
answer += mp[sum - i];
if (mp.ContainsKey(sum - 1))
mp[sum - 1]++;
else
mp[sum - 1] = 1;
}
Console.Write(answer - 2);
}
public static void Main(String []args)
{
int []arr = {1, 0, 2, 1,
2, -2, 2, 4};
int N = arr.Length;
countOfSubarray(arr, N);
}
}
|
Javascript
<script>
function countOfSubarray(arr, N)
{
var mp = new Map();
var answer = 0;
var sum = 0;
if (!mp.has(1))
mp.set(1, 1)
else
mp.set(1, mp.get(1)+1)
for ( var i = 0; i < N; i++) {
sum += arr[i];
answer += mp.has(sum - i)?mp.get(sum - i):0;
if (mp.has(sum - i))
mp.set(sum - i, mp.get(sum - i)+1)
else
mp.set(sum - i, 1)
}
document.write( answer);
}
var arr = [1, 0, 2, 1, 2, -2, 2, 4];
var N = arr.length;
countOfSubarray(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...