Pairs with Difference less than K | JavaScript code to find count of Pairs with difference less than K . ; To sort the array . ; Keep incrementing result while subsequent elements are within limits . ; Driver code
function countPairs ( a , n , k ) { a . sort ( ( a , b ) => a - b ) ; let res = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let j = i + 1 ; while ( j < n && a [ j ] - a [ i ] < k ) { res ++ ; j ++ ; } } return res ; } let a = [ 1 , 10 , 4 , 2 ] ; let k = 3 ; let n = a . length ; document . write ( countPairs ( a , n , k ) + " " ) ;