Pairs with Difference less than K | Python 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
def countPairs ( a , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < n and a [ j ] - a [ i ] < k ) : NEW_LINE INDENT res += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT a = [ 1 , 10 , 4 , 2 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n , k ) , end = " " ) NEW_LINE