I was tring a codingninjas problem, while executing got only 1 test case satisfied, please help.
Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x.
While printing a triplet, print the smallest element first.
That is, if a valid triplet is (6, 5, 10) print "5 6 10". There is no constraint that out of 5 triplets which have to be printed on 1st line. You can print triplets in any order, just be careful about the order of elements in a triplet.
Sample Input
7
1 2 3 4 5 6 7
12
Sample Output
1 4 7
1 5 6
2 3 7
2 4 6
3 4 5
This is my code
#include<iostream>
using namespace std;
void FindTriplet(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)
{
if(arr[i]<arr[j] && arr[i]<arr[k])
{
if(arr[j]<arr[k])
cout << arr[i] << " "<< arr[j] << " " << arr[k] <<endl;
else
cout << arr[i] << " "<< arr[k] << " " << arr[j] <<endl;
}
else if(arr[j]<arr[i] && arr[j]<arr[k])
{
if(arr[i]<arr[k])
cout << arr[j] << " "<< arr[i] << " " << arr[k] <<endl;
else
cout << arr[j] << " "<< arr[k] << " " << arr[i] <<endl;
}
else
{
if(arr[i]<arr[j])
cout << arr[k] << " "<< arr[i] << " " << arr[j] <<endl;
else
cout << arr[k] << " "<< arr[j] << " " << arr[i] <<endl;
}
}
}
}
}
}
int main()
{
int size;
int x;
cin>>size;
int *input=new int[1+size];
for(int i=0;i<size;i++)
cin>>input[i];
cin>>x;
FindTriplet(input,size,x);
return 0;
}
What would happen if there the triplet consists of 2 equal numbers on the i-th and j-th position, and arr[k] > arr[i]
? For example (1, 1, 2)
with the required sum 4
?
The expression arr[i]<arr[j] && arr[i]<arr[k]
is false. The same is true for arr[j]<arr[i] && arr[j]<arr[k]
. So you fall into the else
branch (arr[k]<arr[i] && arr[k]<arr[j]
), and this is not true.