Tuesday, January 24, 2012

Find all triplets in an array such that "a - b = c".


Given a sorted array, output all triplets <a,b,c> such that a-b = c. Expected time is O(n^2). 


Input Array:
-12, -7, -4, 0, 3, 5, 9, 10, 15, 16


Code Output:
-12 -7 -4 0 3 5 9 10 15 16 
Number of triplets for "a-b=c":6
-7 -12 5 
-4 -7 3 
3 -12 15 
3 -7 10 
5 -4 9 
9 -7 16 


Approach:
1. For every A[i], have 2 pointers in the array say j at the A[0] and k at A[n-1].
2. Check the expression (A[i] == A[j]+A[k]), if false then do ++j or --k depending on (A[i] < A[j]+A[k]) or (A[i] > A[j]+A[k]).
3. When you are moving the pointers just make sure that (j != i) and (k != i).
4. Store the triplets in the hashMap and in the end print those triplets.

No comments:

Post a Comment