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 ; Driver code ; Given array ; Given size ; Function Call
def countPairs ( arr , n ) : NEW_LINE INDENT mp1 = { } NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE mp1 [ sum ] = mp1 . get ( sum , 0 ) + 1 NEW_LINE DEDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum in mp1 ) : NEW_LINE INDENT ans += mp1 [ sum ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE countPairs ( arr , n ) NEW_LINE DEDENT