Count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ] | Function to count total number of required tuples ; Initialize unordered map ; Find the pairs ( j , l ) such that arr [ j ] = arr [ l ] and j < l ; Elements are equal ; Update the count ; Add the frequency of arr [ l ] to val ; Update the frequency of element arr [ j ] ; Return the answer ; Given array arr [ ] ; Function Call
function countTuples ( arr , N ) { var ans = 0 , val = 0 ; var freq = new Map ( ) ; for ( var j = 0 ; j < N - 2 ; j ++ ) { val = 0 ; for ( var l = j + 1 ; l < N ; l ++ ) { if ( arr [ j ] == arr [ l ] ) { ans += val ; } if ( freq . has ( arr [ l ] ) ) { val += freq . get ( arr [ l ] ) ; } } if ( freq . has ( arr [ j ] ) ) { freq . set ( arr [ j ] , freq . get ( arr [ j ] ) + 1 ) ; } else { freq . set ( arr [ j ] , 1 ) ; } } return ans ; } var arr = [ 1 , 2 , 1 , 2 , 2 , 2 ] ; var N = arr . length ; document . write ( countTuples ( arr , N ) ) ;