All unique triplets that sum up to a given value | C ++ program to find all unique triplets without using any extra space . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriplets ( int a [ ] , int n , int sum ) { int i ; sort ( a , a + n ) ; bool flag = false ; for ( i = 0 ; i < n - 2 ; i ++ ) { if ( i == 0 a [ i ] > a [ i - 1 ] ) { int start = i + 1 ; int end = n - 1 ; int target = sum - a [ i ] ; while ( start < end ) { if ( start > i + 1 && a [ start ] == a [ start - 1 ] ) { start ++ ; continue ; } if ( end < n - 1 && a [ end ] == a [ end + 1 ] ) { end -- ; continue ; } if ( target == a [ start ] + a [ end ] ) { cout << " [ " << a [ i ] << " , " << a [ start ] << " , " << a [ end ] << " ] ▁ " ; flag = true ; start ++ ; end -- ; } else if ( target > ( a [ start ] + a [ end ] ) ) { start ++ ; } else { end -- ; } } } } if ( flag == false ) { cout << " No ▁ Such ▁ Triplets ▁ Exist " << " STRNEWLINE " ; } } int main ( ) { int a [ ] = { 12 , 3 , 6 , 1 , 6 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int sum = 24 ; findTriplets ( a , n , sum ) ; return 0 ; }