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
function countPairs ( arr ) { let N = arr . length ; let ans = 0 ; let M = new Map ( ) ; for ( let i = 0 ; i < arr . length ; i ++ ) { if ( M . has ( arr [ i ] ) ) { M . get ( arr [ i ] ) . push ( i ) ; } else { M . set ( arr [ i ] , [ i ] ) } } for ( let it of M ) { let v = it [ 1 ] ; let sum = 0 ; for ( let j = 0 ; j < v . length ; j ++ ) { ans += sum * ( N - v [ j ] ) ; sum += v [ j ] + 1 ; } } document . write ( ans ) ; } let arr = [ 1 , 2 , 1 , 1 ] ; countPairs ( arr ) ;