Count all distinct pairs with difference equal to k | Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < sum ; Driver code
def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while r < n : NEW_LINE INDENT if arr [ r ] - arr [ l ] == k : NEW_LINE INDENT count += 1 NEW_LINE l += 1 NEW_LINE r += 1 NEW_LINE DEDENT elif arr [ r ] - arr [ l ] > k : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT 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 DEDENT