All unique triplets that sum up to a given value | Function to all find unique triplets without using extra space ; Sort the input array ; For handling the cases when no such triplets exits . ; Iterate over the array from start to n - 2. ; Index of the first element in remaining range . ; Index of the last element ; Setting our new target ; Checking if current element is same as previous ; Checking if current element is same as previous ; If we found the triplets then print it and set the flag ; If target is greater then increment the start index ; If target is smaller than decrement the end index ; If no such triplets found ; Driver code ; Function call
def findTriplets ( a , n , sum ) : NEW_LINE INDENT a . sort ( ) NEW_LINE flag = False NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( i == 0 or a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT start = i + 1 NEW_LINE end = n - 1 NEW_LINE target = sum - a [ i ] NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( start > i + 1 and a [ start ] == a [ start - 1 ] ) : NEW_LINE INDENT start += 1 NEW_LINE continue NEW_LINE DEDENT if ( end < n - 1 and a [ end ] == a [ end + 1 ] ) : NEW_LINE INDENT end -= 1 NEW_LINE continue NEW_LINE DEDENT if ( target == a [ start ] + a [ end ] ) : NEW_LINE INDENT print ( " [ " , a [ i ] , " , " , a [ start ] , " , " , a [ end ] , " ] " , end = " ▁ " ) NEW_LINE flag = True NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT elif ( target > ( a [ start ] + a [ end ] ) ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT end -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " No ▁ Such ▁ Triplets ▁ Exist " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 12 , 3 , 6 , 1 , 6 , 9 ] NEW_LINE n = len ( a ) NEW_LINE sum = 24 NEW_LINE findTriplets ( a , n , sum ) NEW_LINE DEDENT