One test case is showing message TIMELIMIT i.e exceeding timelimit

What should i do now in this Problem
Code is
#include
#include
using namespace std;
int main() {int n,i;
cin>>n;
int arr[n];
int g=0;
while(g<n)
{
cin>>arr[g];
g++;
}
/for(i=0;i<n;i++)
{
cin>>arr[i];
}
/
int target;
cin>>target;
sort(arr,arr+n);
int l=0;
int r=n-1;
while(l<r)
{
if(arr[r]+arr[l]>target)
{
r=r-1;
}
else if (arr[r]+arr[l]==target)
{
cout<<arr[l]<<" and "<<arr[r]<<endl;
l=l+1;
r=r-1;

}
}
return 0;
}

Hi ramit,
You have not included the case when arr[r] and arr[l]<target. In this you need to this l++;
Hope it helps:)

This is my final code then :

#include

#include
using namespace std;
int main() {int n,i;
cin>>n;
int arr[n];
int g=0;
while(g<n)
{
cin>>arr[g];
g++;
}
int target;
cin>>target;
sort(arr,arr+n);
int l=0;
int r=n-1;
while(l<r)
{
if(arr[r]+arr[l]>target)
{
r=r-1;
}
else if (arr[r]+arr[l]==target)
{
cout<<arr[l]<<" and "<<arr[r]<<endl;
l=l+1;
r=r-1;

}
else
{
l++;
}
}
return 0;
}
But after all the correct test cases it is not showing a Green Tick

This two pointer approach may not work in case of duplicate elements like array = {1,1,1,1} and sum = 2
ans = (1,1), (1,1), (1,1), (1,1), (1,1), (1,1)
but your code gives (1,1), (1,1)
you may use hashing for this purpose

Hope it helps :slight_smile: