Count the pairs in an array such that the difference between them and their indices is equal | Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
def countPairs ( arr , n ) : NEW_LINE INDENT map = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT map [ arr [ i ] - i ] = map . get ( arr [ i ] - i , 0 ) + 1 NEW_LINE DEDENT res = 0 NEW_LINE for x in map : NEW_LINE INDENT cnt = map [ x ] NEW_LINE res += ( ( cnt * ( cnt - 1 ) ) // 2 ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 5 , 6 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE