Find all triplets in an array with a given sum | Solution - 2 | Using Binary Search

preview_player
Показать описание
In this video, we are solving a coding question, "Find all the triplets in an array that add up to a given sum".

We have previously solved a question similar to this one in our previous videos, which is to "Find a pair that adds up to a given sum", and you can watch that video in the following link.

When you face interviews with Big Tech companies like Google, Amazon, Facebook, Microsoft, Apple, you may face this kind of questions.
For any coding question, there isn't a single approach or a single solution to solve the problem. There will be multiple ways, and which approach we are going to take purely depends on the complete picture of the question.
This particular question of finding triplets with given sum can be solved in at least four different ways. I am going to show you how you can solve in 4 different ways in this video, and in the rest of the videos in this playlist.

We have already talked about the Brute-Force technique of solving this problem, which is to find all triplets in the array, and check if any of those combinations add up to given sum. The time complexity of Brute-force technique is O(n^3). The complete Brute-Force solution can be found in the following link.

In this video, we are optimizing the Brute-Force technique by reducing the time complexity from O(n^3) to O(n^2logn). The basic idea of the approach is to first sort the array and find the first element of the triplet by iterating over the array, and for each first element selected, iterate over the rest of the array to find the second element. For each of the first and second element selected, we calculate the third element which can add to the given sum and search in the remaining array using Binary Search.

You can find the complete solution in my blog as well, and here is the link for it.

#Coding #Interviews #Java #FindTripletsWithASum #BinarySearch
Рекомендации по теме
Комментарии
Автор

Thank you for uploading different solutions 👍

varasriboddupalli
Автор

in sop, it should be search not arr[k]

naveensagarushi