See the very most optimized solution to find triplet that sum to a given value in sorted array in java. We can solve it in O(n^2) time complexity and O(1) extra space.
See the running code to find the triplet of given sum:-
//If arry not sorted then first of all sort the array O(n log n) and find the pairs.
//Unsorted array Time Complexity O(n log n)+O(n^2).
//Don't use hashing because hashing will require O(n)extra space. So, bellow approach is better
//Time Complexity O(n^2)
private static boolean isTripletInSortedArray1(int[] arr, int sum) {
//Base check
if(arr.length < 3)
return false;
int len = arr.length;
//O(n)
for(int i=0; i<len; i++) {
//O(n)
if(isPair(arr, i+1, len-1, sum-arr[i])) {
System.out.println(arr[i]+"]");
return true;
}
}
return false;
}
//Time Complexity O(n)
private static boolean isPair(int[] arr, int left, int right, int sum) {
int start=left, end=right;
while(start<end) {
if(arr[start]+arr[end]==sum) {
System.out.print("Pair: ["+arr[start]+", "+ arr[end]+", ");
return true;
}
if(arr[start]+arr[end] > sum) {
end--;
}else {
start++;
}
}
return false;
}