I’ m getting the correct output , but still all the testcases are showing failed. I don’t know what’ s wrong. Please help.
Something's off with my code
Please share the code.
EDIT: Okay, I retrieved it from your recent submission, I hope it is the same.
#include
#include
using namespace std;
int main() {
int n;
cin >> n;
int arr[n] = {0};
for(int i = 0; i < n; i++){
cin >> arr[i];
}
int target;
cin >> target;
sort(arr , arr+n);
int l = 0;
int r = n-1;
int tar = 0;
for(int i = 0; i<n; i++){
l = i+1;
int remtar = target - arr[i];
while(l<r){
tar = arr[l] + arr[r];
if(remtar == tar) {
cout << arr[i] << ", " << arr[l] << " and " << arr[r] << endl;
l++;
}
else if(remtar > tar) l++;
else r–;
}
}
return 0;
}
The question probably only asks for unique triplets., but your code will print duplicates as well.
I can’t see how my code does that, can you tell one example where it might show such behavior
for
5
1 1 1 1 1
3
your code will ouput,
1, 1 and 1
1, 1 and 1
1, 1 and 1
1, 1 and 1
1, 1 and 1
1, 1 and 1
I am not sure but looks like the question only wants
1, 1 and 1
I made the change in my code to avoid the duplicates. It’s still failing. Given below is my code, please tell what’s wrong–
#include
#include
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n] = {0};
for(int i = 0; i < n; i++){
cin >> arr[i];
}
int target;
cin >> target;
sort(arr , arr+n);
int l = 0;
int r = n-1;
int tar = 0;
int com[3] = {0};
int remtar = 1;
for(int i = 0; i<n; i++){
l = i+1;
if(remtar == tar) break;
remtar = target - arr[i];
while(l<r){
tar = arr[l] + arr[r];
if(remtar == tar) {
cout << arr[i] << ", " << arr[l] << " and " << arr[r] << endl;
com[0] = arr[i];
com[1] = arr[l];
com[2] = arr[r];
break;
}
else if(remtar > tar) l++;
else r–;
}
}
int check[3] = {0};
for(int i = 0; i<n; i++){
l = i+1;
int rem = target - arr[i];
while(l<r){
tar = arr[l] + arr[r];
if(rem == tar) {
check[0] = arr[i];
check[1] = arr[l];
check[2] = arr[r];
int fincheck = memcmp ( com, check, sizeof(com) );
if(fincheck != 0)
cout << arr[i] << ", " << arr[l] << " and " << arr[r] << endl;
l++;
}
else if(remtar > tar) l++;
else r–;
}
}
return 0;
}
Note: Use ide.codingblocks.com or any other online ide to share your code.
I found mistakes in your original code, let’s first rectify those, then we will see if the question asks for unique or not.
You need to reset l and r for every i, else you will lose a lot of possible answers.
for example,
9
9 8 7 6 5 4 3 2 1
12
Your code won’t find “2 3 7”.
Okay, got it. Now it’s working fine. Thanks for the help. Much appreciated