1. `findTriplets` function takes an array `arr` and its size `n` as input.
2. It sorts the array using `Arrays.sort`, which takes O(n*log(n)) time.
3. It iterates through the sorted array: - Calls `getTriplet` function with the current element and its index. - `getTriplet` searches for a pair that sums to the negative of the current element. - If found, it returns the triplet as an ArrayList.
4. Inside `getTriplet`: - It iterates through the array from the beginning to the current index. - Calls `check` function to search for a pair that sums to the target value. - If found, returns the triplet; otherwise, continues the search.
5. The `check` function searches for a value in the array and returns its index or -1 if not found.
6. Overall time complexity: - Sorting: O(n*log(n)) - Iterating through the array: O(n) - Search within `getTriplet` and `check`: O(n) each, but nested.
7. The dominant factor is sorting, so the overall time complexity is O(n*log(n)).
import java.util.* ;
import java.io.*;
public class Solution
{
public static int check(int arr[], int sum, int index ){
int i = 0;
// System.out.println("finding pair for "+ sum);
while(i < index){
if(arr[i] > sum){
// System.out.println("Not found");
return -1;
}
if(arr[i] == sum){
return i;
}
i++;
}
return -1;
}
public static ArrayList<Integer> getTriplet(int arr[], int index, int sum){
int i = 0;
// System.out.println("finding MAIN pair for "+ sum);
ArrayList<Integer> ans = new ArrayList<Integer>();
int otherIndex = -1;
while(i < index){
if(arr[i] > sum){
// System.out.println("not found");
ans.clear();
return ans;
}
otherIndex = check(arr,sum-arr[i], i);
if(otherIndex != -1){
// System.out.println("Found");
ans.add(arr[i]);
ans.add(arr[otherIndex]);
return ans;
}
else{
// System.out.println("not found for "+ sum);
}
i++;
}
ans.clear();
return ans;
}
public static ArrayList<Integer> findTriplets(int[] arr, int n)
{
//Write your code here.
ArrayList<Integer> triplet = new ArrayList<>();
Arrays.sort(arr);
int i= 0;
try{
while(i < arr.length){
triplet = getTriplet(arr,i, arr[i]);
if(triplet.size() == 2 ){
triplet.add(arr[i]);
return triplet;
}
i++;
}
}
catch(Exception e){
System.out.println(e);
}
return triplet;
}
}