Count unordered pairs of equal elements for all subarrays | Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse the map M ; Traverse the array ; Update the value of ans ; Update the value of the sum ; Print the value of ans ; Driver Code
def countPairs ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE ans = 0 NEW_LINE M = { } NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] in M : NEW_LINE INDENT M [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT M [ arr [ i ] ] = [ i ] NEW_LINE DEDENT DEDENT for key , value in M . items ( ) : NEW_LINE INDENT v = value NEW_LINE sum1 = 0 NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT ans += ( sum1 * ( N - v [ j ] ) ) NEW_LINE sum1 += v [ j ] + 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE countPairs ( arr ) NEW_LINE DEDENT