Not working right

#include
#include
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int key;
cin>>key;
sort(arr,arr+n);
int i=0;int j=n-1;
while(i<j)
{
if(arr[i]+arr[j]==key)
{
cout<<arr[i]<<" and "<<arr[j]<<endl;
i++;j++;
}
if(arr[i]+arr[j]>key)
{
j–;
}
else{
i++;
}
}
return 0;
}

test case 2 is note working why???
code is similar to solution.

Hello Utkarsh, just don’t do

either do i++ or j-- (so that every pair is taken care of)

But if i take the case as
10
2 2 2 4 4 4 4 4 4 4
sum=6

than total pairs should be 21 times 2 4…
but gives only 7 times of it…

Yes you have a valid point!
This cannot be dealt in O(n) complexity!
instead you should iterate for every element, and check for valid sum across all elements which brings complexity to O(n^2).
Pseudo Code would be:
for i: 0 to n-1
for j: i+1 to n-1
if(a[i]+a[j]==sum)
print a[i],a[j]

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.