Open In App

Find all triplets that sum to a given value or less

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads