Given an unsorted integer array, find a triplet with a given sum in it.

For example,

Input:
 
nums = [ 2, 7, 4, 0, 9, 5, 1, 3 ]
target = 6
 
Output: Triplet exists.
 
The triplets with the given sum 6 are {0, 1, 5}, {0, 2, 4}, {1, 2, 3}

Practice this problem

The problem is a standard variation of the 3SUM problem, where instead of looking for numbers whose sum is 0, we look for numbers whose sum is any constant C.

1. Naive Recursive Approach

The idea is similar to the 0–1 Knapsack problem and uses recursion. We either consider the current item or exclude it and recur for the remaining elements for each item. Return true if we get the desired sum by including or excluding the current item. Following is the implementation in C++, Java, and Python based on the idea:

C++


Download  Run Code

Output:

Triplet exists

Java


Download  Run Code

Output:

Triplet exists

Python


Download  Run Code

Output:

Triplet exists

We can also use three nested loops and consider every triplet in the given array to check if the desired sum is found.

2. Using Hashing

The idea is to insert each array element into a hash table. Then consider all pairs present in the array and check if the remaining sum exists in the map or not. If the remaining sum is seen before and triplet doesn’t overlap with each other, i.e., (i, j, i) or (i, j, j), print the triplet and return. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Triplet exists

Java


Download  Run Code

Output:

Triplet exists

Python


Download  Run Code

Output:

Triplet exists

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the size of the input.

3. Printing distinct triplets

The idea is to sort the given array in ascending order, and for each element nums[i] in the array, check if the triplet is formed by nums[i] and a pair from subarray nums[i+1…n). This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

(0 1 5)
(0 2 4)
(1 2 3)

Java


Download  Run Code

Output:

(0 1 5)
(0 2 4)
(1 2 3)

Python


Download  Run Code

Output:

(0, 1, 5)
(0, 2, 4)
(1, 2, 3)

The time complexity of the above solution is O(n2) and doesn’t require any extra space.