You are given an array ‘ARR’ containing ‘N’ integers.
Return all the unique triplets [ARR[i], ARR[j], ARR[k]] such that i != j, j != k and k != i and their sum is equal to zero.
Input: ‘N’ = 5
'ARR' = [-1, -1, 2, 0, 1]
Output:
-1 -1 2
-1 0 1
Explanation:
(-1 -1 +2) = (-1 +0 +1) = 0.
The first line contains an integer, ‘N’, representing the number of elements in the array.
The next line contains ‘N’ space-separated integers representing the elements of the array.
Output format:
Return an integer, the number of all the unique triplets with zero-sum.
5
-1 -1 2 0 1
-1 -1 2
-1 0 1
(-1 -1 +2) = (-1 +0 +1) = 0.
4
0 0 0 0
0 0 0
1 <= N <= 1000
1 <= ARR[i] <= 1000
Time Limit: 1 sec
Try the problem after sorting the given array.
Approach:
The solution to the problem lies in first sorting the array, then we can apply the two pointers approach. The two pointers approach would be traversing the array from one side and then for the fixed element we can find other two elements using two pointers approach as the array is sorted now.
The steps are as follows:
Function [][int] triplet( int ‘N’, [int] ‘ARR’ )
O( N * N ), Where N is the size of the array.
For the worst case, we are iterating all the elements once in the outer loop, then we are using the two-pointers approach inside the loop.
Hence the time complexity is O( N * N ).
O(K * 3), Where K is the number of unique triplets.
We are using space for storing all the triplets.
Hence the space complexity is O(K * 3).