Monday, January 23, 2012

Find triplets that sum to zero in an array.


Print triplets that sum to 0 in an integers array.


Approach:
1. Sort the Array say A[].
2. Keep three pointers i, j, and k. 0<=i<n-2, j=i+1 and k=n-1
3. Now for every i, check if (A[i] + A[j] + A[k]) == 0, if so we have our triplet otherwise do ++j or --k depending on whether (A[i] + A[j] + A[k]) is less than zero or greater than zero.


Time complexity: O(n^2).


Example:
int [] A = {1, 2, -5, 4, -2, 3, -19, 10, 5, 8, -25, 19, 6, 20, -10, -7, -3};


Output:
-25 -19 -10 -7 -5 -3 -2 1 2 3 4 5 6 8 10 19 20 
Number of triplets that sum to zero:13
-25 5 20 
-25 6 19 
-10 2 8 
-10 4 6 
-7 -3 10 
-7 1 6 
-7 2 5 
-7 3 4 
-5 -3 8 
-5 1 4 
-5 2 3 
-3 -2 5 
-3 1 2 

No comments:

Post a Comment