Target Sum Triplets

I can pass the given sample input test case but I am unable to pass anyother test cases I don’t know why,

Though I have followed the given hint.

here’s my code

#include
#include
using namespace std;

void getTripletPair(int arr[], int n, int target)
{
//sort(arr, arr+n);
int i=0, left=0, right=0;
for(i=0; i<n-3; i++)
{
left = i+1;
right = n-1;

	while(left<right)
	{
		int sum = arr[i] + arr[left] + arr[right];

		if(sum==target)
		{
			cout << arr[i] << ',' << arr[left] << " and " << arr[right]<<endl;
			left++;
		}
		else if(sum>target)
		{
			right--;
		}
		else//if(sum<target)
		{
			left++;
		}
	}
}

}

int main() {
int n;
cin >> n;

int arr[n];

for(int i=0; i<n; i++)
{
	cin >> arr[i];
}

int target;
cin >> target;

sort(arr, arr+n);

getTripletPair(arr, n, target);

return 0;

}

Hi @Udit-Sehra-2366292823468769
There is a space error because after printing comma there should be space before printing 2nd element.
It should be like this :
cout << arr[i] << ", " << arr[left] << " and " << arr[right]<<endl;

And also after printing the triplet then you have to increment left as well as right to get new triplet.

Here is your corrected code :

1 Like

Thank you very much✌

Hi @Udit-Sehra-2366292823468769
Mark the doubt as resolved if you got where your code was failing.

Okay, sorry I forgot about that
Thanks for reminding me.