Skip to content

Commit 12a5693

Browse files
committed
Added 3Sum.cpp (div-bargali#113)
1 parent 56cfae2 commit 12a5693

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

C++/Algorithms/3Sum.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Given an array of n integers, are there elements a, b, c in nums such that a + b + c = 0?
3+
Find all unique triplets in the array which gives the sum of zero.
4+
Notice that the solution set must not contain duplicate triplets.
5+
*/
6+
7+
/* Sample inputs and outputs
8+
Input: arr = [-1,0,1,2,-1,-4]
9+
Output: [-1,-1,2] [-1,0,1]
10+
11+
Input: arr= [0]
12+
Output: []
13+
*/
14+
15+
#include <iostream>
16+
#include <bits/stdc++.h>
17+
using namespace std;
18+
19+
20+
//Function to check if triplet with sum = 0 exists
21+
void threeSum(int arr[],int n) {
22+
23+
sort(arr,arr + n);
24+
for(int i = 0; i < n; i++)
25+
{
26+
if(i != 0 && arr[i] == arr[i-1])continue;
27+
int j = i+1, k = n-1;
28+
while(j < k)
29+
{
30+
int sum = arr[i] + arr[j] + arr[k];
31+
if(sum == 0)
32+
{
33+
cout<<"[ "<<arr[i]<<", "<<arr[j]<<", "<<arr[k]<<"] ";
34+
j++;
35+
while (j < k && arr[j] == arr[j-1]) j++;
36+
37+
}
38+
else if (sum > 0) k--;
39+
else j++;
40+
}
41+
}
42+
43+
}
44+
45+
//Driver code to test the threeSum function
46+
int main(){
47+
48+
int arr[]={ -1, 0, 1, 2, -1, -4 };
49+
int n = 6;
50+
51+
threeSum(arr,n);
52+
53+
return 0;
54+
}

0 commit comments

Comments
 (0)