Arrays target sum triplets test cases issue

Hi,

The code which I’ve written works for the example test case in the question. However, only one test case has been passed when I’ve tried to submit the code. Can you please check and let me know what’s wrong with the code?

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int j = 0; j < n; j++) {
int arrVal = sc.nextInt();
arr[j] = arrVal;
}
bubbleSort(arr);
int check = sc.nextInt();
for (int i = 0; i < n-2; i++) {
int left = i+1;
int right = n-1;
while(left < right) {
int condition = arr[left] + arr [right] + arr[i];
if(condition == check) {
System.out.println(arr[i] + ", "+ arr[left] + " and " + arr [right] );
left ++;
right --;
} else {
right --;
}
}
}

}

public static void bubbleSort (int arr []) {
	for (int i = 0; i < arr.length; i++) {
		for (int j = 0; j < arr.length-1-i; j++) {
			if(arr[j] > arr[j+1]) {
				int temp = arr[j];
				arr[j]=arr[j+1];
				arr[j+1]=temp;
			}
		}
	}

Hey @patnamsainikhil The problem with your code was
i) while loop condition should be left <= right not left < right.
ii) You should add condition like this
if(condition == check) {

System.out.println(arr[i] + ", "+ arr[left] + " and " + arr [right] );

left ++;

right --;

} else if(condition > check){

right --;

}else{

left++;

}
You only mentioned the condition for right–;
and finally your code will look like(for next time try to put your on coding blocks ide then share the link it will be easy for me ) : https://ide.codingblocks.com

1 Like

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.

thank you, problem solved