Given an array of integers, are there elements in such that ? Find all unique triplets in the array which gives the sum of zero.
Note:

Elements in a triplet must be in non-descending order. (i.e., )

The solution set must not contain duplicate triplets.

INPUT: = {-1, 0, 1, 2, -1, -4}
OUTPUT: (-1, 0, 1) and (-1, -1, 2)

Thoughts:
Apparently a algorithm exists but we can ignore it. To do better than that, we notice that if we can afford , we can first sort in . Does sorting help us in any way? The answer is definitely yes because it points out the direction of search for us. We can have a algorithm:
At outer loop, we iterate through every position from 0 to . For a particular position , we look at all the element between to (remeber that they are all sorted). We initialize two pointers and . In the inner loop, we compute the sum . If s is bigger than 0, then we know we need to find something smaller, we decrease . If s is smaller than 0, then we know we need to find something bigger, so we increase . If the sum is exactly 0, we mark the triplet down and put it into the solution set (in order to find all of the solutions, we need to decrease and increase at the same time for this case). We continue this process until exceeds . Therefore, the worst case for inner loop is to look at everything between to . But each time we increase by 1 at outer loop, we have 1 less element needed to look at inner loop. Explicitly, the overall running time is given by .