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 to test above function
function countPairsWithDiffK ( arr , n , k ) { count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] - arr [ j ] == k arr [ j ] - arr [ i ] == k ) count ++ ; } return count ; } arr = new Array ( 1 , 5 , 3 , 4 , 2 ) ; n = arr . length ; k = 3 ; document . write ( " " + countPairsWithDiffK ( arr , n , k ) ) ;