Given is a array of numbers:
1, 2, 8, 6, 9, 0, 4
We need to find all the numbers in group of three which sums to a value N ( say 11 in this example). Here, the possible numbers in group of three are:
{1,2,8}, {1,4,6}, {0,2,9}
The first solution I could think was of O(n^3). Later I could improve a little(n^2 log n) with the approach:
1. Sort the array.
2. Select any two number and perform binary search for the third element.
Can it be improved further with some other approaches?
You can certainly do it in
O(n^2): for eachiin the array, test whether two other values sum toN-i.You can test in
O(n)whether two values in a sorted array sum tokby sweeping from both ends at once. If the sum of the two elements you’re on is too big, decrement the “right-to-left” index to make it smaller. If the sum is too small, increment the “left-to-right” index to make it bigger. If there’s a pair that works, you’ll find them, and you perform at most2*niterations before you run out of road at one end or the other. You might need code to ignore the value you’re using asi, depends what the rules are.You could instead use some kind of dynamic programming, working down from
N, and you probably end up with time something likeO(n*N)or so. Realistically I don’t think that’s any better: it looks like all your numbers are non-negative, so ifnis much bigger thanNthen before you start you can quickly throw out any large values from the array, and also any duplicates beyond 3 copies of each value (or 2 copies, as long as you check whether3*i == Nbefore discarding the 3rd copy ofi). After that step,nisO(N).