Count pairs of indices having equal prefix and suffix sums | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int * arr , int n ) { unordered_map < int , int > mp1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; mp1 [ sum ] += 1 ; } sum = 0 ; int ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( mp1 . find ( sum ) != mp1 . end ( ) ) { ans += mp1 [ sum ] ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , n ) ; return 0 ; }