The program is meant to find and return the number of triplets sum in the array/list which is equal to any integer value X.
triplets = (any three elements in array list)
The array can be in any order
Say, array size =7
Sample input : {1, 2, 3, 4, 5, 6, 7}
X = 12
Sample Output : 5
by reducing operations, I mean to reduce time complexity. As I wrote this code :
public static int tripletSum(int[] arr, int num) {
int count = 0;
for(int i = 0; i<arr.length; i++){
for(int j = i+1; j<arr.length; j++){
for (int k = j+1; k<arr.length; k++){
if ((arr[i] + arr[j] + arr[k])==num){
count++;
}
}
}
}
return count;
}
}
I get O(n^3) time complexity using this code and Time limit Exceeded error with this. Any way to reduce it to O(n^2) ?