In this video we will learn how to find all triplets with the given sum in the given array in Java.
In this we will be discussing the brute force solution which is easy to understand and simple as well. Then we will try to optimize the code using Java Collections Framework.
Approaches to find all triplets with the given sum in the given array:
Method 1: Brute Force Solution
We will select each possible triplet and them add them to get their sum if the sum is equal to the target value then we will print that triplet. To select all three possible pairs we will have to use nested loops. Because of using nested loops the time complexity of this method is high but as we are not using extra space the space complexity remains constant.
Method 2: By using HashSet
The main idea behind this approach is that if Target - a[i] - a[j] is present in the array then we can say that the target sum is possible and the triplet will be (a[i], a[j], Target - a[i] - a[j]). To use this approach we will be using extra space due to which space complexity of the algorithm increases but the time complexity decreases as compare to the brute force solution.