I was thinking of various approaches for finding the triplet sum and I came across this finding a triplet having a given sum. So I thought of giving it a try.
My algorithm:
1) Sort the numbers //O(nlogn)
2) Initialize low=0 and high=size-1
3) loop till low<high
a) if sum-arr[high]-arr[low]< 0 , then decrement high
b) if third number is not in range of (low,high) then break the loop
c) else search for third number using binary search
But I am not getting correct output. I don't know where my logic is wrong because its pretty much simple binary search. Below is what I have implemented. Please let me know my mistake
static boolean isTriplet(int a[], int size, int sum)
{
Arrays.sort(a); //sort the numbers
int low = 0;
int high = size-1;
while(low<high)
{
int third = sum - a[high] - a[low];
if(third<0)
high--;
else if(!(sum - a[high] - a[low]>a[low] && sum - a[high] - a[low]< a[high])) //if the number is not within the range then no need to find the index
break;
else
{
int index = binarySearch(a,low+1,high-1,third);
if(index != -1)
{
System.out.println(a[low]+" "+a[index]+" "+a[high]);
return true;
}
else
low++;
}
}
return false;
}
I tried it with input {1,2,3,4,5,6}
and sum=6 but it returns false and when input was {3,4,8,1,2,7,5}
and sum=20 it returned true