Find all unique triplets that sum to zero
Problem:
Given a set S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the set which gives the sum of zero.
Given a set S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the set which gives the sum of zero.
For example, given set S = {-1 0 1 2 -1 -4},
One possible solution set is:
(-1, 0, 1)
(-1, 2, -1)
(-1, 0, 1)
(-1, 2, -1)
Note that (0, 1, -1) is not part of the solution above, because (0, 1, -1) is the duplicate of (-1, 0, 1). Same with (-1, -1, 2).
For a set S, there is probably no “the” solution, another solution could be:
(0, 1, -1)
(2, -1, -1)
(0, 1, -1)
(2, -1, -1)
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| set<arrayList< int > > findTriplets( int [] a) { // Sort the array a = sort(a); int [ 3 ] triplet; set<triplet> triplets; int n = a.length(); for ( int i = 0 ;i < n- 2 ; i++) { int j = i + 1 ; int k = n - 1 ; while (j < k) { int sum_two = arr[i] + arr[j]; if (sum_two + arr[k] < 0 ) { j++; } else if (sum_two + arr[k] > 0 ) { k--; } else { triplet[ 0 ] = arr[i]; triplet[ 1 ] = arr[j]; triplet[ 2 ] = arr[k]; triplets.insert(triplet); j++; k--; } } } return triplets; } |
Click here for more Programming Interview Questions
No comments:
Post a Comment