Print triplets with sum less than k
Given an array of distinct integers and a sum value. Print all triplets with sum smaller than given sum value. Expected Time Complexity is O(n2).
Examples:
Input : arr[] = {-2, 0, 1, 3}
sum = 2.
Output : (-2, 0, 1)
(-2, 0, 3)
Explanation : The two triplets have sum less than 2.
Input : arr[] = {5, 1, 3, 4, 7}
sum = 12.
Output : (1, 3, 4)
(1, 3, 5)
(1, 3, 7)
(1, 4, 5)
A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and print current triplet if its sum is smaller than given sum.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int printTriplets( int arr[], int n, int sum)
{
for ( int i = 0; i < n-2; i++)
{
for ( int j = i+1; j < n-1; j++)
{
for ( int k = j+1; k < n; k++)
if (arr[i] + arr[j] + arr[k] < sum)
cout << arr[i] << ", " << arr[j]
<< ", " << arr[k] << endl;
}
}
}
int main()
{
int arr[] = {5, 1, 3, 4, 7};
int n = sizeof arr / sizeof arr[0];
int sum = 12;
printTriplets(arr, n, sum);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int printTriplets( int arr[],
int n, int sum)
{
for ( int i = 0 ; i < n - 2 ; i++)
{
for ( int j = i + 1 ;
j < n - 1 ; j++)
{
for ( int k = j + 1 ; k < n; k++)
if (arr[i] + arr[j] + arr[k] < sum)
System.out.println(arr[i] + ", " +
arr[j] + ", " +
arr[k]);
}
}
return 0 ;
}
public static void main (String[] args)
{
int arr[] = { 5 , 1 , 3 , 4 , 7 };
int n = arr.length;
int sum = 12 ;
printTriplets(arr, n, sum);
}
}
|
Python3
def printTriplets(arr, n, sum ):
for i in range ( 0 , n - 2 , 1 ):
for j in range (i + 1 , n - 1 , 1 ):
for k in range (j + 1 , n, 1 ):
if (arr[i] + arr[j] + arr[k] < sum ):
print (arr[i], "," , arr[j], "," , arr[k])
if __name__ = = '__main__' :
arr = [ 5 , 1 , 3 , 4 , 7 ]
n = len (arr)
sum = 12
printTriplets(arr, n, sum )
|
C#
using System;
class GFG
{
static int printTriplets( int [] arr,
int n, int sum)
{
for ( int i = 0; i < n - 2; i++)
{
for ( int j = i + 1;
j < n - 1; j++)
{
for ( int k = j + 1; k < n; k++)
if (arr[i] + arr[j] + arr[k] < sum)
Console.WriteLine(arr[i] + ", " +
arr[j] + ", " +
arr[k]);
}
}
return 0;
}
public static void Main ()
{
int [] arr = {5, 1, 3, 4, 7};
int n = arr.Length;
int sum = 12;
printTriplets(arr, n, sum);
}
}
|
PHP
<?php
function printTriplets(& $arr , $n , $sum )
{
for ( $i = 0; $i < $n - 2; $i ++)
{
for ( $j = $i + 1; $j < $n - 1; $j ++)
{
for ( $k = $j + 1; $k < $n ; $k ++)
if ( $arr [ $i ] + $arr [ $j ] +
$arr [ $k ] < $sum )
{
echo ( $arr [ $i ]);
echo ( ", " );
echo ( $arr [ $j ]);
echo ( ", " );
echo ( $arr [ $k ]);
echo ( "\n" );
}
}
}
}
$arr = array (5, 1, 3, 4, 7);
$n = sizeof( $arr );
$sum = 12;
printTriplets( $arr , $n , $sum );
?>
|
Javascript
<script>
function printTriplets(arr, n, sum)
{
for (let i = 0; i < n-2; i++)
{
for (let j = i+1; j < n-1; j++)
{
for (let k = j+1; k < n; k++)
if (arr[i] + arr[j] + arr[k] < sum)
document.write(arr[i] + ", " + arr[j]
+ ", " + arr[k] + "<br>" );
}
}
}
let arr = [5, 1, 3, 4, 7];
let n = arr.length;
let sum = 12;
printTriplets(arr, n, sum);
</script>
|
Output
5, 1, 3
5, 1, 4
1, 3, 4
1, 3, 7
Time complexity : O(n3)
Auxiliary Space: O(1)
An Efficient Solution can print triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop.
1) Sort the input array in increasing order.
2) Initialize result as 0.
3) Run a loop from i = 0 to n-2. An iteration of this loop
finds all triplets with arr[i] as first element.
a) Initialize other two elements as corner elements
of subarray
arr[i+1..n-1], i.e., j = i+1 and k = n-1
b) Move j and k toward each other until they meet,
i.e., while (j = sum), then do k--
// Else for current i and j, there are (k-j) possible
// third elements that satisfy the constraint.
(ii) Else print elements from j to k
Below is the implementation of above idea.
C++
#include <bits/stdc++.h>
using namespace std;
int printTriplets( int arr[], int n, int sum)
{
sort(arr, arr + n);
for ( int i = 0; i < n - 2; i++) {
int j = i + 1, k = n - 1;
while (j < k) {
if (arr[i] + arr[j] + arr[k] >= sum)
k--;
else {
for ( int x = j + 1; x <= k; x++)
cout << arr[i] << ", " << arr[j]
<< ", " << arr[x] << endl;
j++;
}
}
}
}
int main()
{
int arr[] = { 5, 1, 3, 4, 7 };
int n = sizeof arr / sizeof arr[0];
int sum = 12;
printTriplets(arr, n, sum);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static void printTriplets( int arr[],
int n, int sum)
{
Arrays.sort(arr);
for ( int i = 0 ; i < n - 2 ; i++)
{
int j = i + 1 , k = n - 1 ;
while (j < k)
{
if (arr[i] + arr[j] + arr[k] >= sum)
k--;
else
{
for ( int x = j + 1 ; x <= k; x++)
System.out.println(arr[i] + ", " +
arr[j] + ", " +
arr[x]);
j++;
}
}
}
}
public static void main(String args[])
{
int arr[] = { 5 , 1 , 3 , 4 , 7 };
int n = arr.length;
int sum = 12 ;
printTriplets(arr, n, sum);
}
}
|
Python3
def printTriplets(arr, n, sum ):
arr.sort()
for i in range (n - 2 ):
(j, k) = (i + 1 , n - 1 )
while (j < k):
if (arr[i] + arr[j] + arr[k] > = sum ):
k - = 1
else :
for x in range (j + 1 , k + 1 ):
print ( str (arr[i]) + ", " +
str (arr[j]) + ", " +
str (arr[x]))
j + = 1
if __name__ = = "__main__" :
arr = [ 5 , 1 , 3 , 4 , 7 ]
n = len (arr)
sum = 12
printTriplets(arr, n, sum );
|
C#
using System;
class GFG
{
static void printTriplets( int [] arr,
int n, int sum)
{
Array.Sort(arr);
for ( int i = 0; i < n - 2; i++)
{
int j = i + 1, k = n - 1;
while (j < k)
{
if (arr[i] + arr[j] + arr[k] >= sum)
k--;
else
{
for ( int x = j + 1; x <= k; x++)
Console.WriteLine(arr[i] + ", " +
arr[j] + ", " +
arr[x]);
j++;
}
}
}
}
public static void Main()
{
int [] arr = { 5, 1, 3, 4, 7 };
int n = arr.Length;
int sum = 12;
printTriplets(arr, n, sum);
}
}
|
PHP
<?php
function printTriplets( $arr , $n , $sum )
{
sort( $arr , 0);
for ( $i = 0; $i < $n - 2; $i ++)
{
$j = $i + 1; $k = $n - 1;
while ( $j < $k )
{
if ( $arr [ $i ] + $arr [ $j ] +
$arr [ $k ] >= $sum )
$k --;
else
{
for ( $x = $j + 1; $x <= $k ; $x ++)
echo $arr [ $i ] . ", " . $arr [ $j ] .
", " . $arr [ $x ] . "\n" ;
$j ++;
}
}
}
}
$arr = array (5, 1, 3, 4, 7);
$n = sizeof( $arr );
$sum = 12;
printTriplets( $arr , $n , $sum );
?>
|
Javascript
<script>
function printTriplets(arr, n, sum)
{
arr.sort( function (a, b){ return a - b});
for (let i = 0; i < n - 2; i++)
{
let j = i + 1, k = n - 1;
while (j < k)
{
if (arr[i] + arr[j] + arr[k] >= sum)
k--;
else
{
for (let x = j + 1; x <= k; x++)
document.write(arr[i] + ", " +
arr[j] + ", " +
arr[x] + "</br>" );
j++;
}
}
}
}
let arr = [ 5, 1, 3, 4, 7 ];
let n = arr.length;
let sum = 12;
printTriplets(arr, n, sum);
</script>
|
Output
1, 3, 4
1, 3, 5
1, 3, 7
1, 4, 5
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Print triplets with sum less than k in python:
Python3
def print_triplets(arr, k):
n = len (arr)
count = 0
arr.sort()
for i in range (n - 2 ):
j = i + 1
k = n - 1
while j < k:
triplet_sum = arr[i] + arr[j] + arr[k]
if triplet_sum < k:
print (arr[i], arr[j], arr[k])
count + = 1
j + = 1
else :
k - = 1
return count
arr = [ 5 , 1 , 3 , 4 , 7 ]
k = 12
count = print_triplets(arr, k)
print ( "Total number of triplets with sum less than" , k, "is" , count)
|
Output
Total number of triplets with sum less than 12 is 0
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Approach:
1.Define a function print_triplets that takes two arguments: an array arr and an integer k. The function will return the count of triplets with sum less than k.
2.Get the length of the array n, and initialize a variable count to 0 to keep track of the number of triplets.
3.Sort the input array arr in non-decreasing order, using the built-in sort() function. This is done to simplify the algorithm and allow us to stop iterating when we find a triplet with sum greater than or equal to k.
4.Use a nested loop to iterate through all possible triplets of the input array arr. The outer loop will iterate from the first element to the second to last element, while the inner loop will iterate from the element following the current outer loop element to the last element.
5.For each triplet, calculate the sum of the triplet triplet_sum as the sum of the current outer loop element, the current inner loop element, and the last element of the array.
6.If triplet_sum is less than k, print the triplet and increment the count variable by 1.
7.If triplet_sum is greater than or equal to k, decrement the index of the last element of the array to move to the next smaller element, and continue checking triplets.
8.After iterating through all possible triplets, return the count of triplets with sum less than k.
9.In the example usage, create an input array arr and an integer k, and call the print_triplets function with these arguments. Finally, print the total number of triplets found.
Time complexity: O(n^2), where n is the size of the input array
Space complexity: O(1)
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...