Find Triplet with Given Sum in an Array

Find triplet with given sum in an array.

Given an array of unsorted integers and a value k. Write a code to determine whether or not there exist three elements in array whose sum is equal to k.

Return true if triplet exist else return false.

For example:

Example 1:

Input: {1, 4, 45, 6, 10, 8} k = 13 Output: true (1, 4, 8)

Example 2:

Input: {2, 7, 4, 0, 9, 5, 1, 3} k = 6
Output: true {(2, 4, 0), (5, 1, 0), (1, 2, 3)}

Find Triplet with given sum in an array

This problem is similar to find triplets with zero sum. So, we have to find three numbers of an array whose sum is equal to given value k.

We have discussed the problem statement. Let’s discuss how we can solve this problem efficiently. Also, At the end of this post, i have mentioned the link of video tutorial in which i have explained multiple approaches and their time complexities.

Programming video tutorials

Method 1: Brute Force Approach

The simplest approach is to use three for loops to generate all triplets and compare every sum with given value k. If triplet exist then return true else return false.

The time complexity of this approach is O(n^3).

Find pairs with given sum in a sorted array

Find Triplet with Given Sum in an Array using Sorting

We can reduce the time complexity, if we first sort the array and then run two for loop to find triplets whose sum is equal to given value k.

The time complexity of this approach is O(n^2).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.