Please look into the code, it is not giving any output.
Arrays-Target Sum Triplets
Just dry run and check. Your 2-pointer approach is wrong. In the else case you are doing left++ and right-- which is not correct.
It is similar to array target sum pair problem.
Step 1: First Sort the array.
Step 2: Fix an element at i. Then find the rest two elements that sum to target in the similar way you have done the array target sum pair.
Consider the sorted array: [1 2 3 4 5 6 7]
Initially
- i points to first element
- l points to the left of the remaining array ie. to i+1
- r points to the right of remaining array ie. to the last element.
for every i:
if(arr[l]+arr[r]+arr[i]==target)
print the possibility, l++, r–
if(arr[l]+arr[r]+arr[i]>target)
r–
if(arr[l]+arr[r]+arr[i]<target)
l++
continue these steps till (l<r) -->after that increment i by one position and repeat the same steps.
For reference check this https://ide.codingblocks.com/s/261890
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.