Given an unsorted integer array, print all triplets in it with sum less than or equal to a given number.

For example,

Input:
 
nums = [ 2, 7, 4, 9, 5, 1, 3 ]
sum = 10
 
Output: Triplets are
 
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 2, 7)
(1, 3, 4)
(1, 3, 5)
(1, 4, 5)
(2, 3, 4)
(2, 3, 5)

Practice this problem

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

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 2, 7)
(1, 3, 4)
(1, 3, 5)
(1, 4, 5)
(2, 3, 4)
(2, 3, 5)

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

 
We can also solve this problem using backtracking, as shown below. Thanks to Tamara Vasylenko for suggesting this alternative approach.

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 7], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5]]

Python


Download  Run Code

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 7], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5]]