Target Sum Pair

My code is not passing the last test case. Please help

#include<bits/stdc++.h>
using namespace std;
void target_sum(int a[], int n, int target)
{
int left = 0;
int right = n-1;
bool sum_found = false;
while(left<=right)
{
int sum = a[right]+a[left];
if(sum<target)
{
left++;
}

    else if(sum>target)
    {
        right--;
    }
    else
    {
        cout<<a[left]<<" and "<<a[right]<< endl;
        left++;
        right--;         
        sum_found= true;
        
    }
}

if(!sum_found)
{
    cout<<"Sum is not found";

}
}

int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int x;
cin>>x;
sort(arr,arr+n);
target_sum(arr,n,x);
}

Hello @Rahulranjan916,

You need to modify your while loop condition, it should be left < right.
If for some array, left == right and sum == target then in that case you are printing a[left] and a[right] but left and right are the same elements.

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.