Problem - Given an Array of integers, A. Find out if there exists a triple (i,j,k) such that A[i] + A[j] + A[k] == 0.The 3SUM problem is very similar to the 2SUM problem in many aspects. The solutions I'll be discussing are also very similar. I highly recommend you read the previous post first, since I'll explain only the differences in the algorithm from the previous post.
Let's begin, We start with the naive algorithm. An O(n^3) solution with 3 nested loops each checking if the sum of the triple is 0. Since O(n^3) is the higher order term, we can sort the array in O(nlogn) and add a guard at the nested loops to prune of parts of the arrays. But the complexity still remains O(n^3).
The code is pretty simple and similar to the naive algorithm of 2SUM.
And now finally, we're going to use the left-right method (for lack of a better name).This time we keep one element as a constant and then for each element A[i], we run the 2SUM Linear Algorithm for A[i+1...n] That gives us a O(n^2) algorithm.
Comments
Post a Comment