Skip to content

Commit 6d7e6fa

Browse files
Merge pull request #650 from divyaachoudharyy/new_branch
Triplet sum
2 parents 28577da + 3810c17 commit 6d7e6fa

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Arrays/triplet_sum.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/******************************************************************************
2+
3+
Given an array arr of size n and an integer X.
4+
Find if there's a triplet in the array which sums up to the given integer X.
5+
6+
*******************************************************************************/
7+
8+
//SOLUTION (in C++)
9+
10+
#include <bits/stdc++.h>
11+
12+
using namespace std;
13+
14+
void findTripletSum(int A[], int n, int X)
15+
{
16+
sort(A, A+n); //sort the array, it becomes easy to take the sum.
17+
int i, j, k, count = 0;
18+
for(i = 0;i<=n-3;i++) //i should only run till n-3 as we need three numbers for a triplet.
19+
{
20+
j = i+1;
21+
k = n-1;
22+
while(j<k) //two-pointer appraoch is used.
23+
{
24+
if(A[i] + A[j] + A[k] < X) //since the array is sorted, if the sum if less than X, the we need to increment j.
25+
{
26+
j++;
27+
}
28+
else if(A[i] + A[j] + A[k] > X) //If the sum is greater than X, we need to decrement k.
29+
{
30+
k--;
31+
}
32+
else if(A[i] + A[j] + A[k] == X) //If the sum is equal to X we need to increement j and decrement k, so that we may find other combinations of the given sum.
33+
{
34+
j++;
35+
k--;
36+
count++;
37+
}
38+
}
39+
}
40+
if(count == 0)
41+
cout<<"The triplet doesn't exists"<<endl;
42+
else
43+
cout<<"The triplet exists"<<endl;
44+
}
45+
46+
int main()
47+
{
48+
int n, X;
49+
cout<<"Enter n"<<endl;
50+
cin>>n;
51+
cout<<"Enter the sum you want to find"<<endl;
52+
cin>>X;
53+
cout<<"Enter the array elements"<<endl;
54+
int A[n];
55+
for(int i = 0;i<n;i++)
56+
{
57+
cin>>A[i];
58+
}
59+
findTripletSum(A, n, X);
60+
return 0;
61+
}

0 commit comments

Comments
 (0)