Count pairs with average present in the same array | javascript implementation of the approach ; Function to return the count of valid pairs ; Frequency array Twice the original size to hold negative elements as well ; Update the frequency of each of the array element ; If say x = - 1000 then we will place the frequency of - 1000 at ( - 1000 + 1000 = 0 ) a [ 0 ] index ; To store the count of valid pairs ; Remember we will check only for ( even , even ) or ( odd , odd ) pairs of indexes as the average of two consecutive elements is a floating povar number ; Driver code
var N = 1000 ; function countPairs ( arr , n ) { var size = ( 2 * N ) + 1 ; var freq = Array ( size ) . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) { var x = arr [ i ] ; freq [ x + N ] ++ ; } var ans = 0 ; for ( i = 0 ; i < size ; i ++ ) { if ( freq [ i ] > 0 ) { ans += ( ( freq [ i ] ) * ( freq [ i ] - 1 ) ) / 2 ; for ( j = i + 2 ; j < 2001 ; j += 2 ) { if ( freq [ j ] > 0 && ( freq [ ( i + j ) / 2 ] > 0 ) ) { ans += ( freq [ i ] * freq [ j ] ) ; } } } } return ans ; } var arr = [ 4 , 2 , 5 , 1 , 3 , 5 ] ; var n = arr . length ; document . write ( countPairs ( arr , n ) ) ;