what should be a better option then sort?
Better approach then this as test cases failing time limit
@lakshay2311 No sort is a must. But your loop is the issue here, you arenβt making any updates to i or j if a[i]+a[j] is not equal to target so it runs for eternity and causes TLE.
Instead use this snippet of code to calculate the pairs after sorting.
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++){
if(a[i]+a[j]==target) cout<<a[i]<<" and "<<a[j]<<endl;
}
can you make changes in the code and add comments?
Yeah here is the changed code, I removed your loop with this implementation https://ide.codingblocks.com/s/187789
1 Like