One obvious solution is to examine each possible triplet of the array and check if there is a triplet with sum = 0. But this takes O(n3) time and is not efficient for large arrays.
A better approach would be to sort the array first in increasing order. Follow this iterative algorithm.
- Fix the first element, start two pointers one at the begin and the other at the end of the sorted array.
- If the sum of the three elements is zero return.
- If the sum is greater than zero, we decrement the end pointer so that the sum moves closer to zero
- If the sum is negative, we increment the begin pointer to add up value to sum.
- Iterate this procedure until the fixed element moves towards the end.
This procedure takes O(n log n) for sorting the array and O(n2) for actually finding the triplet. So the overall time complexity would be O(n2) and O(1) extra space.
Here is the java code to do this.