I was given a tricky question. Given: A = [a1,a2,...an] (list of positive integers with length \"n\") r (positive integer)
Find a list
Here is another approach that might be helpful. It is sometimes known as a "meet-in-the-middle" algorithm and runs in O(n * 2^(n/2))
. The basic idea is this. Suppose n = 40
and you know that the middle slot is a +
. Then, you can brute force all N := 2^20
possibilities for each side. Let A
be a length N
array storing the possible values of the left side, and similarly let B
be a length N
array storing the values for the right side.
Then, after sorting A
and B
, it is not hard to efficiently check for whether any two of them sum to r
(e.g. for each value in A
, do a binary search on B
, or you can even do it in linear time if both arrays are sorted). This part takes O(N * log N) = O(n * 2^(n/2))
time.
Now, this was all assuming the middle slot is a +
. If not, then it has to be a *
, and you can combine the middle two elements into one (their product), reducing the problem to n = 39
. Then you try the same thing, and so on. If you analyze it carefully, you should get O(n * 2^(n/2))
as the asymptotic complexity, since actually the largest term dominates.
You need to do some bookkeeping to actually recover the +
's and *
's, which I have left out to simplify the explanation.