Find a triplet that sums to a given value
2 min readApr 23, 2021
I came across this question on the GeeksForGeeks platform and found their solution not much satisfactory, So I submit an improvement for that and that got published and now the article is improved.
https://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24;
Output: 12, 3, 9
Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
Input: array = {1, 2, 3, 4, 5}, sum = 9
Output: 5, 3, 1
Explanation: There is a triplet (5, 3 and 1) present
in the array whose sum is 9.
Here Comes my Solution for the same.
Time Complexity O(n²), Space complexity O(1)
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int arr = {12, 3, 4, 1, 6, 9}, sum = 24;
find(arr,sum);
}
public static void find(int[] arr, int sum)
{
int i = 0, j = 1, k = 2;
Arrays.sort(arr);
sum -= arr[i] + arr[j] + arr[k];
boolean kFlag = true, jFlag = true;
while (sum > 0) {
if (k < arr.length - 1 && kFlag) {
sum += arr[k];
k++;
sum -= arr[k];
if (sum < 0) {
sum += arr[k];
k--;
sum -= arr[k];
kFlag = false;
}
}
else if (j < k - 1 && jFlag) {
sum += arr[j];
j++;
sum -= arr[j];
if (sum < 0) {
sum += arr[j];
j--;
sum -= arr[j];
jFlag = false;
}
}
else {
sum += arr[i];
i++;
sum -= arr[i];
}
}
System.out.println(arr[k] + " " + arr[j] + " "
+ arr[i]);
}
}
The code is self-explanatory.
Happy Coding!