Count of subarrays having sum equal to its length | Java 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
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 ) ) ; } }