text: Count of subarrays having sum equal to its length | Set 2 | Java program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Store count of elements upto current element with length i ; Stores the final count of subarray ; Stores the prefix sum ; If size of subarray is 1 ; Iterate the array ; Find the sum ; Update frequency in map ; Print the total count ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
code: 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 ) ; } }