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 program
function countPairsWithDiffK ( arr , n , k ) { let count = 0 ; arr . sort ( ) ; let l = 0 ; let r = 0 ; while ( r < n ) { if ( arr [ r ] - arr [ l ] == k ) { count ++ ; l ++ ; r ++ ; } else if ( arr [ r ] - arr [ l ] > k ) l ++ ; else r ++ ; } return count ; } let arr = [ 1 , 5 , 3 , 4 , 2 ] ; let n = arr . length ; let k = 3 ; document . write ( " " + countPairsWithDiffK ( arr , n , k ) ) ;