Count pairs of indices having equal prefix and suffix sums | C # code for 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
using System ; using System . Collections . Generic ; class GFG { static void countPairs ( int [ ] arr , int n ) { Dictionary < int , int > mp1 = new Dictionary < int , int > ( ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( mp1 . ContainsKey ( sum ) ) { mp1 . Add ( sum , mp1 [ sum ] + 1 ) ; } else { mp1 . Add ( sum , 1 ) ; } } sum = 0 ; int ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( mp1 . ContainsKey ( sum ) ) { ans += mp1 [ sum ] ; } } Console . Write ( ans ) ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 1 , 1 } ; int n = arr . Length ; countPairs ( arr , n ) ; } }