This is my code for Target sum pairs and this matches the editorial and still the final output on submitting does not pass all test cases, please let me know the error

#include<bits/stdc++.h>
using namespace std;
int main() {

int *arr = new int[10000];
int n;
cin>>n;

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

sort(arr, arr + n);
int left = 0;
int right = n;
while (left < right)
{
    int sum = arr[left] + arr[right];
    if (sum > n)
    {
        right--;
    }
    else if (sum < n)
    {
        left++;
    }
    else
    {
        cout << arr[left] << " and " << arr[right] << endl;
        left++;
        right--;
    }
}
return 0;

}

in order to avoid duplicate triplets from getting printed u need to run a while loop for the digits that are same


the 2 while loops on line 33 & 34 are impt

#include<bits/stdc++.h>
using namespace std;
int main() {

int *arr = new int[10000];
int n;
cin>>n;

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

sort(arr, arr + n);
int left = 0;
int right = n;
while (left < right)
{
    int sum = arr[left] + arr[right];
    if (sum > n)
    {
        right--;
    }
    else if (sum < n)
    {
        left++;
    }
    else
    {
        cout << arr[left] << " and " << arr[right] << endl;
        while(arr[left] == arr[left+1] && left+1 < right)
		{
			left++;
		}
		while(arr[right] == arr[right-1] && right-1 > left)
		{
			right--;
		}
        left++;
        right--;
    }
}
return 0;

}

I have written do let me know the error thanks.

share code in cb ide

@dtewari2001

Hey, i am extremely sorry it seems i messed this
like i thought this is target triplet sum and provided the code for the same

but now i realise that this is pair sum

u can simply make a map of all elements and the index at which they exist and iterate for left side and check if target- a[i] exist in map which does not have index same as present i th index

  1. why in for loop you iterate from 0 to n ( it gives you a total of n+1 elements whereas you have to input only n numbers), so it should be from 0 to (n-1).

  2. you have to compare sum with your target variable and not with the size of the array.

1 Like

I do not know how to make a map in C++. will try .

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.