Find k ordered pairs in array with minimum difference d | Function to find the required pairs ; There has to be atleast 2 * k elements ; To store the pairs ; Sort the given array ; For every possible pair ; If the current pair is valid ; Insert it into the pair vector ; If k pairs are not possible ; Print the pairs ; Driver code
def findPairs ( arr , n , k , d ) : NEW_LINE INDENT if ( n < 2 * k ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT pairs = [ ] NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( arr [ n - k + i ] - arr [ i ] >= d ) : NEW_LINE INDENT pairs . append ( [ arr [ i ] , arr [ n - k + i ] ] ) NEW_LINE DEDENT DEDENT if ( len ( pairs ) < k ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for v in pairs : NEW_LINE INDENT print ( " ( " , v [ 0 ] , " , ▁ " , v [ 1 ] , " ) " ) NEW_LINE DEDENT DEDENT arr = [ 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE d = 3 NEW_LINE findPairs ( arr , n , k , d ) NEW_LINE