Find all triplets that sum to a given value or less
Last Updated :
03 Apr, 2023
Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X.
Example:
Input : arr[] = {-1, 1, 3, 2}, X = 3
Output: (-1, 1, 3), (-1, 1, 2)
Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose sum is less than or equal to 3.
Approach: This can be solved with the following idea:
- Here, we use the Two-pointer approach. The first requirement is to sort the given array, which is done using the sort function from C++ STL.
- Then, we put 2 pointers (j at left end after iterator i and k at rightmost end) at either end of the array while maintaining an iterator from 0th index.
- Now, we decrement the k pointer if the sum of triplet at indices (i, j, k) is greater than sum. If it is not, then as we have sorted the array before checking for triplets, we can be sure that any triplet from the sub array:
- arr = {i, j, j+1, j+2, ... n}
- Will have sum less than or equal to k (given value), whenever
- arr[i] + arr[j] + arr[n] <=k
Steps involved in the implementation of code:
- Sort the given array.
- After sorting, start iterating from 0 to N - 2.
- In a loop of i, start another iterator such that j = i + 1 and k = N - 1.
- Check if the sum of elements at i, j, and k is less than X or not.
- If, it is fewer print elements at i, j, and k
- Else if the sum comes out to be more than X, reduce k by 1
- Else increment j by 1
Below is the implementation of the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to pribt triplets
void triplet(int arr[], int size, int sum)
{
// Sorting the passed array
sort(arr, arr + size);
for (int i = 0; i < size - 2; i++) {
// Setting two pointer for
// the subarray [j, ...k]
int j = i + 1, k = size - 1;
while (j < k) {
// Decrement the right corner
// if triplet sum is greater
// than required value
if ((arr[i] + arr[j] + arr[k]) > sum) {
k--;
}
else {
// If the triplet sum is
// equal or less than
// required value then
// printing then printing
// all the values at indices
// i, j and between j+1
// and k, as the array
// is sorted
for (int n = j + 1; n <= k; n++) {
printf("(%d, %d, %d)\n", arr[i], arr[j],
arr[n]);
}
j++;
}
}
}
}
// Driver code
int main()
{
int size = 5;
int arr[size] = { 1, 2, 3, -4, 5 };
// Function call
triplet(arr, size, 3);
}
Java
// Java code for the above approach
import java.util.Arrays;
public class GFG {
// Function to print triplets
public static void triplet(int arr[], int size, int sum)
{
// Sorting the passed array
Arrays.sort(arr);
for (int i = 0; i < size - 2; i++) {
// Setting two pointer for
// the subarray [j, ...k]
int j = i + 1, k = size - 1;
while (j < k) {
// Decrement the right corner
// if triplet sum is greater
// than required value
if ((arr[i] + arr[j] + arr[k]) > sum) {
k--;
}
else {
// If the triplet sum is
// equal or less than
// required value then
// printing then printing
// all the values at indices
// i, j and between j+1
// and k, as the array
// is sorted
for (int n = j + 1; n <= k; n++) {
System.out.printf("(%d, %d, %d)\n",
arr[i], arr[j],
arr[n]);
}
j++;
}
}
}
}
// Driver code
public static void main(String[] args)
{
int size = 5;
int[] arr = { 1, 2, 3, -4, 5 };
// Function call
triplet(arr, size, 3);
}
}
C#
using System;
class Program {
// Function to print triplets
static void triplet(int[] arr, int size, int sum)
{
// Sorting the passed array
Array.Sort(arr);
for (int i = 0; i < size - 2; i++) {
// Setting two pointer for
// the subarray [j, ...k]
int j = i + 1, k = size - 1;
while (j < k) {
// Decrement the right corner
// if triplet sum is greater
// than required value
if ((arr[i] + arr[j] + arr[k]) > sum) {
k--;
}
else {
// If the triplet sum is
// equal or less than
// required value then
// printing all the values at indices
// i, j and between j+1
// and k, as the array
// is sorted
for (int n = j + 1; n <= k; n++) {
Console.WriteLine(
"(" + arr[i] + ", " + arr[j]
+ ", " + arr[n] + ")");
}
j++;
}
}
}
}
static void Main(string[] args)
{
int size = 5;
int[] arr = new int[] { 1, 2, 3, -4, 5 };
// Function call
triplet(arr, size, 3);
}
}
JavaScript
// JS code for the above approach
// Function to pribt triplets
function triplet(arr, size, sum)
{
// Sorting the passed array
arr.sort();
for (let i = 0; i < size - 2; i++) {
// Setting two pointer for
// the subarray [j, ...k]
let j = i + 1, k = size - 1;
while (j < k) {
// Decrement the right corner
// if triplet sum is greater
// than required value
if ((arr[i] + arr[j] + arr[k]) > sum) {
k--;
}
else {
// If the triplet sum is
// equal or less than
// required value then
// printing then printing
// all the values at indices
// i, j and between j+1
// and k, as the array
// is sorted
for (let n = j + 1; n <= k; n++) {
console.log("("+arr[i]+", "+ arr[j]+", "+ arr[n]+")");
}
j++;
}
}
}
}
// Driver code
let size = 5;
let arr = [ 1, 2, 3, -4, 5 ];
// Function call
triplet(arr, size, 3);
Python3
def triplet(arr, size, sum):
# Sorting the passed array
arr.sort()
for i in range(size - 2):
# Setting two pointer for
# the subarray [j, ...k]
j = i + 1
k = size - 1
while j < k:
# Decrement the right corner
# if triplet sum is greater
# than required value
if arr[i] + arr[j] + arr[k] > sum:
k -= 1
else:
# If the triplet sum is
# equal or less than
# required value then
# printing then printing
# all the values at indices
# i, j and between j+1
# and k, as the array
# is sorted
for n in range(j + 1, k + 1):
print("({}, {}, {})".format(arr[i], arr[j], arr[n]))
j += 1
# Driver code
if __name__ == "__main__":
size = 5
arr = [1, 2, 3, -4, 5]
# Function call
triplet(arr, size, 3)
Output(-4, 1, 2)
(-4, 1, 3)
(-4, 1, 5)
(-4, 2, 3)
(-4, 2, 5)
Time Complexity: O(N2)
Auxiliary Space: O(1)
Similar Reads
Javascript Program to Find a triplet that sum to a given value Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is
6 min read
Count triplets with sum smaller than a given value Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input :
11 min read
3 Sum - Find all Triplets with Given Sum Given an array arr[] and an integer target, the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to given target and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted o
12 min read
Find a triplet from three linked lists with sum equal to a given number Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "
14 min read
Javascript Program to Count triplets with sum smaller than a given value Given an array of distinct integers and a sum value. Find the count of triplets with a sum smaller than the given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0,
3 min read
Javascript Program to Find all triplets with zero sum Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.Examples : Input : arr[] = {0, -1, 2, -3, 1}Output : (0 -1 1), (2 -3 1)Explanation : The triplets with zero sum are0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5}Output : 1 -2 1Explana
6 min read