Reputation: 2671
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?
Upvotes: 1
Views: 574
Reputation: 279255
You can certainly do it in O(n^2)
: for each i
in the array, test whether two other values sum to N-i
.
You can test in O(n)
whether two values in a sorted array sum to k
by 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 most 2*n
iterations before you run out of road at one end or the other. You might need code to ignore the value you're using as i
, 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 like O(n*N)
or so. Realistically I don't think that's any better: it looks like all your numbers are non-negative, so if n
is much bigger than N
then 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 whether 3*i == N
before discarding the 3rd copy of i
). After that step, n
is O(N)
.
Upvotes: 2