Count pairs with average present in the same array | Python 3 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 point number ; Driver code
N = 1000 NEW_LINE def countPairs ( arr , n ) : NEW_LINE INDENT size = ( 2 * N ) + 1 NEW_LINE freq = [ 0 for i in range ( size ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE freq [ x + N ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT ans += int ( ( ( freq [ i ] ) * ( freq [ i ] - 1 ) ) / 2 ) NEW_LINE for j in range ( i + 2 , 2001 , 2 ) : NEW_LINE INDENT if ( freq [ j ] > 0 and ( freq [ int ( ( i + j ) / 2 ) ] > 0 ) ) : NEW_LINE INDENT ans += ( freq [ i ] * freq [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 5 , 1 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT