Count pairs of indices having equal prefix and suffix sums | Java program for the above approach ; Function to find the count of index pairs having equal prefix and suffix sums ; Maps indices with prefix sums ; Traverse the array ; Update prefix sum ; Update frequency in Map ; Traverse the array in reverse ; Update suffix sum ; Check if any prefix sum of equal value exists or not ; Print the obtained count ; Driver code ; Given array ; Given size ; Function Call
import java . util . * ; class GFG { static void countPairs ( int [ ] arr , int n ) { HashMap < Integer , Integer > mp1 = new HashMap < Integer , Integer > ( ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( mp1 . containsKey ( sum ) ) { mp1 . put ( sum , mp1 . get ( sum ) + 1 ) ; } else { mp1 . put ( sum , 1 ) ; } } sum = 0 ; int ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( mp1 . containsKey ( sum ) ) { ans += mp1 . get ( sum ) ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int n = arr . length ; countPairs ( arr , n ) ; } }