Count all distinct pairs with difference equal to k | A simple program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver program
def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ i ] - arr [ j ] == k or arr [ j ] - arr [ i ] == k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " , countPairsWithDiffK ( arr , n , k ) ) NEW_LINE