DEV Community

Jayesh Adwani
Jayesh Adwani

Posted on

Find all unique triplets that sum upto 0

Initially I struggled to find the right approach to the problem. I used 3 pointers thought it would save the performance cases. But I was wrong there, this is a two pointer problem after sorting.

Approach: for an index i, take j and k such that, arr[i] + arr[j] +arr[k] equals 0.
If sum < 0, j++,
If sum > 0, k--,
If sum = 0, j++, k--,

Handle duplicates for i,j,k by comparing current to next index elements

Try all combinations using while loop inside a for loop

Time Complexity: O(nlogn) + O(n*m) where m is elements from next to last element.

Space Complexity: O(n)

Top comments (0)