Print triplets with sum less than k | Python3 program to print triplets with sum smaller than a given value ; Sort input array ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there are total k - j third elements . ; Driver code
def printTriplets ( arr , n , sum ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT ( j , k ) = ( i + 1 , n - 1 ) NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT for x in range ( j + 1 , k + 1 ) : NEW_LINE INDENT print ( str ( arr [ i ] ) + " , ▁ " + str ( arr [ j ] ) + " , ▁ " + str ( arr [ x ] ) ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 1 , 3 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 12 NEW_LINE printTriplets ( arr , n , sum ) ; NEW_LINE DEDENT