Count pairs of indices having equal prefix and suffix sums | 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 ; Given array ; Given size ; Function Call
function countPairs ( arr , n ) { let mp1 = new Map ( ) ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( mp1 . has ( sum ) ) { mp1 . set ( sum , mp1 . get ( sum ) + 1 ) ; } else { mp1 . set ( sum , 1 ) } } sum = 0 ; let ans = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( mp1 . has ( sum ) ) { ans += mp1 . get ( sum ) ; } } document . write ( ans ) ; } let arr = [ 1 , 2 , 1 , 1 ] ; let n = arr . length countPairs ( arr , n ) ;