Count of subarrays having sum equal to its length | C # program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Decrementing all the elements of the array by 1 ; Making prefix sum array ; Declare map to store count of elements upto current element ; To count all the subarrays whose prefix sum is 0 ; Iterate the array ; Increment answer by count of current element of prefix array ; Return the answer ; Driver Code ; Given array [ ] arr ; Function call
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 ) ) ; } }