Find three element from different three arrays such that a + b + c = sum
Last Updated :
21 Mar, 2023
Given three integer arrays and a “sum”, the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays.
Examples :
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 9
Output : Yes
1 + 2 + 6 = 9 here 1 from a1[] and 2 from
a2[] and 6 from a3[]
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 20
Output : No
A naive approach is to run three loops and check sum of three element form different arrays equal to given number if find then print exist and otherwise print not exist.
Algorithm:
- Define a function findTriplet that takes in three integer arrays a1, a2, a3, their respective sizes n1, n2, n3, and the integer variable sum.
- Loop through each element of a1, a2, and a3 using three nested for-loops.
- If the sum of the current triplet of elements (a1[i], a2[j], a3[k]) is equal to sum, return true.
- If no such triplet is found, return false.
- In the main function, define three integer arrays a1, a2, a3, and the integer variable sum.
- Get the size of each array using sizeof operator and divide it by the size of a single element to get the size of the array in terms of number of elements.
- Call the findTriplet function with a1, a2, a3, n1, n2, n3, and sum as arguments.
- If the function returns true, print “Yes“. Otherwise, print “No“.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
bool findTriplet( int a1[], int a2[],
int a3[], int n1,
int n2, int n3, int sum)
{
for ( int i = 0; i < n1; i++)
for ( int j = 0; j < n2; j++)
for ( int k = 0; k < n3; k++)
if (a1[i] + a2[j] + a3[k] == sum)
return true ;
return false ;
}
int main()
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9;
int n1 = sizeof (a1) / sizeof (a1[0]);
int n2 = sizeof (a2) / sizeof (a2[0]);
int n3 = sizeof (a3) / sizeof (a3[0]);
findTriplet(a1, a2, a3, n1, n2, n3, sum)?
cout << "Yes" : cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean findTriplet( int a1[], int a2[],
int a3[], int n1,
int n2, int n3, int sum)
{
for ( int i = 0 ; i < n1; i++)
for ( int j = 0 ; j < n2; j++)
for ( int k = 0 ; k < n3; k++)
if (a1[i] + a2[j] + a3[k] == sum)
return true ;
return false ;
}
public static void main (String[] args)
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9 ;
int n1 = a1.length;
int n2 = a2.length;
int n3 = a3.length;
if (findTriplet(a1, a2, a3, n1, n2, n3, sum))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def findTriplet(a1, a2, a3,
n1, n2, n3, sum ):
for i in range ( 0 , n1):
for j in range ( 0 , n2):
for k in range ( 0 , n3):
if (a1[i] + a2[j] +
a3[k] = = sum ):
return True
return False
a1 = [ 1 , 2 , 3 , 4 , 5 ]
a2 = [ 2 , 3 , 6 , 1 , 2 ]
a3 = [ 3 , 2 , 4 , 5 , 6 ]
sum = 9
n1 = len (a1)
n2 = len (a2)
n3 = len (a3)
print ( "Yes" ) if findTriplet(a1, a2, a3,
n1, n2, n3,
sum ) else print ( "No" )
|
C#
using System;
public class GFG
{
static bool findTriplet( int []a1, int []a2,
int []a3, int n1,
int n2, int n3,
int sum)
{
for ( int i = 0; i < n1; i++)
for ( int j = 0; j < n2; j++)
for ( int k = 0; k < n3; k++)
if (a1[i] + a2[j] + a3[k] == sum)
return true ;
return false ;
}
static public void Main ()
{
int []a1 = {1 , 2 , 3 , 4 , 5};
int []a2 = {2 , 3 , 6 , 1 , 2};
int []a3 = {3 , 2 , 4 , 5 , 6};
int sum = 9;
int n1 = a1.Length;
int n2 = a2.Length;
int n3 = a3.Length;
if (findTriplet(a1, a2, a3, n1,
n2, n3, sum))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function findTriplet( $a1 , $a2 , $a3 ,
$n1 , $n2 , $n3 ,
$sum )
{
for ( $i = 0; $i < $n1 ; $i ++)
for ( $j = 0; $j < $n2 ; $j ++)
for ( $k = 0; $k < $n3 ; $k ++)
if ( $a1 [ $i ] + $a2 [ $j ] + $a3 [ $k ] == $sum )
return true;
return false;
}
$a1 = array ( 1 , 2 , 3 , 4 , 5 );
$a2 = array ( 2 , 3 , 6 , 1 , 2 );
$a3 = array ( 3 , 2 , 4 , 5 , 6 );
$sum = 9;
$n1 = count ( $a1 );
$n2 = count ( $a2 );
$n3 = count ( $a3 );
if (findTriplet( $a1 , $a2 , $a3 , $n1 ,
$n2 , $n3 , $sum )==true)
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function findTriplet(a1, a2, a3, n1,
n2, n3, sum)
{
for ( var i = 0; i < n1; i++)
for ( var j = 0; j < n2; j++)
for ( var k = 0; k < n3; k++)
if (a1[i] + a2[j] + a3[k] == sum)
return true ;
return false ;
}
var a1 = [ 1 , 2 , 3 , 4 , 5 ];
var a2 = [ 2 , 3 , 6 , 1 , 2 ];
var a3 = [ 3 , 2 , 4 , 5 , 6 ];
var sum = 9;
var n1 = a1.length;
var n2 = a2.length;
var n3 = a3.length;
findTriplet(a1, a2, a3, n1, n2, n3, sum)?
document.write( "Yes" ) : document.write( "No" );
</script>
|
Time Complexity : O(n3)
Auxiliary Space: O(1)
An efficient solution is to store all elements of first array in hash table (unordered_set in C++) and calculate sum of two elements last two array elements one by one and subtract from given number k and check in hash table if it exists in the hash table then print exist and otherwise not exist.
1. Store all elements of first array in hash table
2. Generate all pairs of elements from two arrays using
nested loop. For every pair (a1[i], a2[j]), check if
sum - (a1[i] + a2[j]) exists in hash table. If yes
return true.
Below is the implementation of above idea.
C++
#include<bits/stdc++.h>
using namespace std;
bool findTriplet( int a1[], int a2[],
int a3[], int n1,
int n2, int n3,
int sum)
{
unordered_set < int > s;
for ( int i = 0; i < n1; i++)
s.insert(a1[i]);
for ( int i = 0; i < n2; i++)
{
for ( int j = 0; j < n3; j++)
{
if (s.find(sum - a2[i] - a3[j]) !=
s.end())
return true ;
}
}
return false ;
}
int main()
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9;
int n1 = sizeof (a1) / sizeof (a1[0]);
int n2 = sizeof (a2) / sizeof (a2[0]);
int n3 = sizeof (a3) / sizeof (a3[0]);
findTriplet(a1, a2, a3, n1, n2, n3, sum)?
cout << "Yes" : cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean findTriplet( int a1[], int a2[], int a3[],
int n1, int n2, int n3,
int sum)
{
HashSet<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n1; i++)
{
s.add(a1[i]);
}
ArrayList<Integer> al = new ArrayList<>(s);
for ( int i = 0 ; i < n2; i++)
{
for ( int j = 0 ; j < n3; j++)
{
if (al.contains(sum - a2[i] - a3[j]) &
al.indexOf(sum - a2[i] - a3[j])
!= al.get(al.size() - 1 ))
{
return true ;
}
}
}
return false ;
}
public static void main(String[] args)
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9 ;
int n1 = a1.length;
int n2 = a2.length;
int n3 = a3.length;
if (findTriplet(a1, a2, a3, n1, n2, n3, sum))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def findTriplet(a1, a2, a3,
n1, n2, n3, sum ):
s = set ()
for i in range (n1):
s.add(a1[i])
for i in range (n2):
for j in range (n3):
if sum - a2[i] - a3[j] in s:
return True
return False
a1 = [ 1 , 2 , 3 , 4 , 5 ]
a2 = [ 2 , 3 , 6 , 1 , 2 ]
a3 = [ 3 , 24 , 5 , 6 ]
n1 = len (a1)
n2 = len (a2)
n3 = len (a3)
sum = 9
if findTriplet(a1, a2, a3,
n1, n2, n3, sum ) = = True :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool findTriplet( int []a1, int []a2, int []a3,
int n1, int n2, int n3,
int sum)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n1; i++)
{
s.Add(a1[i]);
}
List< int > al = new List< int >(s);
for ( int i = 0; i < n2; i++)
{
for ( int j = 0; j < n3; j++)
{
if (al.Contains(sum - a2[i] - a3[j]) &
al.IndexOf(sum - a2[i] - a3[j])
!= al[al.Count - 1])
{
return true ;
}
}
}
return false ;
}
public static void Main(String[] args)
{
int []a1 = {1, 2, 3, 4, 5};
int []a2 = {2, 3, 6, 1, 2};
int []a3 = {3, 2, 4, 5, 6};
int sum = 9;
int n1 = a1.Length;
int n2 = a2.Length;
int n3 = a3.Length;
if (findTriplet(a1, a2, a3, n1, n2, n3, sum))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function findTriplet(a1, a2, a3, n1, n2, n3, sum)
{
var s = new Set();
for ( var i = 0; i < n1; i++)
s.add(a1[i]);
for ( var i = 0; i < n2; i++)
{
for ( var j = 0; j < n3; j++)
{
if (s.has(sum - a2[i] - a3[j]))
return true ;
}
}
return false ;
}
var a1 = [1 , 2 , 3 , 4 , 5];
var a2 = [2 , 3 , 6 , 1 , 2];
var a3 = [3 , 2 , 4 , 5 , 6];
var sum = 9;
var n1 = a1.length;
var n2 = a2.length;
var n3 = a3.length;
findTriplet(a1, a2, a3, n1, n2, n3, sum)?
document.write( "Yes" ): document.write( "No" );
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(n)
Another efficient approach ( Space optimization ) : we will run two loops, then we will search for required sum in third loop using binary search .
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
bool binarysearch( int arr[], int N, int x)
{
int l = 0, r = N - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == x) {
return true ;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return false ;
}
bool findTriplet( int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum)
{ sort(a3,a3+n3);
for ( int i = 0; i < n1; i++)
{
for ( int j = 0; j < n2; j++)
{ int requiredsum= sum-a1[i]-a2[j];
if (binarysearch(a3, n3,requiredsum))
{
return true ;;
}
}
}
return false ;
}
int main()
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum=9;
int n1 = sizeof (a1) / sizeof ( int );
int n2 = sizeof (a2) / sizeof ( int );
int n3 = sizeof (a3) / sizeof ( int );
if (findTriplet(a1, a2, a3, n1, n2, n3,sum))
{
cout<< "YES" <<endl;
}
else {
cout<< "NO" <<endl;
}
return 0;
}
|
Java
import java.util.Arrays;
class Main {
static boolean binarysearch( int arr[], int N, int x)
{
int l = 0 , r = N - 1 ;
while (l <= r) {
int mid = (l + r) / 2 ;
if (arr[mid] == x) {
return true ;
}
else if (arr[mid] < x) {
l = mid + 1 ;
}
else {
r = mid - 1 ;
}
}
return false ;
}
static boolean findTriplet( int a1[], int a2[], int a3[],
int n1, int n2, int n3,
int sum)
{
Arrays.sort(
a3);
for ( int i = 0 ; i < n1; i++) {
for ( int j = 0 ; j < n2; j++) {
int requiredsum = sum - a1[i] - a2[j];
if (binarysearch(a3, n3, requiredsum)) {
return true ;
}
}
}
return false ;
}
public static void main(String[] args)
{
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9 ;
int n1 = a1.length;
int n2 = a2.length;
int n3 = a3.length;
if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) {
System.out.println(
"YES" );
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
def binarysearch(arr, N, x):
l = 0
r = N - 1
while l < = r:
mid = (l + r) / / 2
if arr[mid] = = x:
return True
elif arr[mid] < x:
l = mid + 1
else :
r = mid - 1
return False
def findTriplet(a1, a2, a3, n1, n2, n3, sum ):
a3.sort()
for i in range (n1):
for j in range (n2):
requiredsum = sum - a1[i] - a2[j]
if binarysearch(a3, n3, requiredsum):
return True
return False
if __name__ = = '__main__' :
a1 = [ 1 , 2 , 3 , 4 , 5 ]
a2 = [ 2 , 3 , 6 , 1 , 2 ]
a3 = [ 3 , 2 , 4 , 5 , 6 ]
sum = 9
n1 = len (a1)
n2 = len (a2)
n3 = len (a3)
if findTriplet(a1, a2, a3, n1, n2, n3, sum ):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
using System.Linq;
class Program {
static bool BinarySearch( int [] arr, int n, int x) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == x) {
return true ;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return false ;
}
static bool FindTriplet( int [] a1, int [] a2, int [] a3, int n1, int n2, int n3, int sum) {
Array.Sort(a3);
for ( int i = 0; i < n1; i++) {
for ( int j = 0; j < n2; j++) {
int requiredSum = sum - a1[i] - a2[j];
if (BinarySearch(a3, n3, requiredSum)) {
return true ;
}
}
}
return false ;
}
static void Main( string [] args) {
int [] a1 = { 1, 2, 3, 4, 5 };
int [] a2 = { 2, 3, 6, 1, 2 };
int [] a3 = { 3, 2, 4, 5, 6 };
int sum = 9;
int n1 = a1.Length;
int n2 = a2.Length;
int n3 = a3.Length;
if (FindTriplet(a1, a2, a3, n1, n2, n3, sum)) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function binarysearch(arr, N, x) {
let l = 0;
let r = N - 1;
while (l <= r) {
let mid = Math.floor((l + r) / 2);
if (arr[mid] === x) {
return true ;
} else if (arr[mid] < x) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return false ;
}
function findTriplet(a1, a2, a3, n1, n2, n3, sum) {
a3.sort();
for (let i = 0; i < n1; i++) {
for (let j = 0; j < n2; j++) {
let requiredsum = sum - a1[i] - a2[j];
if (binarysearch(a3, n3, requiredsum)) {
return true ;
}
}
}
return false ;
}
const a1 = [1, 2, 3, 4, 5];
const a2 = [2, 3, 6, 1, 2];
const a3 = [3, 2, 4, 5, 6];
const sum = 9;
const n1 = a1.length;
const n2 = a2.length;
const n3 = a3.length;
if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) {
console.log( "YES" );
} else {
console.log( "NO" );
}
|
Time Complexity: O(n1*n2*log n3)
Auxiliary Space: O(1)
Similar Reads
Find three element from given three arrays such that their sum is X | Set 2
Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A
9 min read
Count of triplets from the given Array such that sum of any two elements is the third element
Given an unsorted array arr, the task is to find the count of the distinct triplets in which the sum of any two elements is the third element. Examples: Input: arr[] = {1, 3, 4, 15, 19} Output: 2 Explanation: In the given array there are two triplets such that the sum of the two elements is equal to
7 min read
Find pairs with given sum such that elements of pair are in different rows
Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row. Examples: Input : mat[][] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10,
15+ min read
Find the largest three distinct elements in an array
Given an array arr[], the task is to find the top three largest distinct integers present in the array. Note: If there are less than three distinct elements in the array, then return the available distinct numbers in descending order. Examples : Input: arr[] = [10, 4, 3, 50, 23, 90]Output: [90, 50,
6 min read
Maximize sum by selecting X different-indexed elements from three given arrays
Given three arrays A[], B[] and C[] of size N and three positive integers X, Y, and Z, the task is to find the maximum sum possible by selecting at most N array elements such that at most X elements are from the array A[], at most Y elements from the array B[], at most Z elements are from the array
15+ min read
Smallest Difference Triplet from Three arrays
Three arrays of same size are given. Find a triplet such that maximum - minimum in that triplet is minimum of all the triplets. A triplet should be selected in a way such that it should have one number from each of the three given arrays. If there are 2 or more smallest difference triplets, then the
10 min read
Find the sum of all values lesser than the element of the Array
Given an integer array arr[] of length n. For each element arr[i], the task is to compute the sum of all elements in the array that are strictly less than arr[i]. Return an array res, where res[i] is the required sum for the element at index i. Examples: Input: arr[] = [1, 2, 3]Output: 0 1 3Explanat
9 min read
Minimize the sum after choosing elements from the given three arrays
Given three arrays A[], B[] and C[] of same size N. The task is to minimize the sum after choosing N elements from these array such that at every index i an element from any one of the array A[i], B[i] or C[i] can be chosen and no two consecutive elements can be chosen from the same array.Examples:
15+ min read
Find four elements a, b, c and d in an array such that a+b = c+d
Given an array arr[] of distinct integers. The task is to determine if there exist two pairs (a, b) and (c, d) such that a + b = c + d, where a, b, c, and d are distinct elements. Note: If multiple solutions exist, return any one valid pair. Examples: Input: arr[] = [3, 4, 7, 1, 2, 9, 8]Output: (3,
13 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] =
15+ min read