Skip to content

Searching an array for sum of values

An answer to this question on Stack Overflow.

Question

I have a system that generates values in a text file which contains values as below

Line 1 : Total value possible

Line 2 : No of elements in the array

Line 3(extra lines if required) : The numbers themselves

I am now thinking of an approach where I can subtract the total value from the first integer in the array and then searching the array for the remainder and then doing the same until the pair is found.

The other approach is to add the two integers in the array on a permutation and combination basis and finding the pair.

As per my analysis the first solution is better since it cuts down on the number of iterations.Is my analysis correct here and is there any other better approach?

Edit : I'll give a sample here to make it more clear Line 1 : 200 Line 2=10 Line 3 : 10 20 80 78 19 25 198 120 12 65

Now the valid pair here is 80,120 since it sums up to 200 (represented in line one as Total Value possible in the input file) and their positions in the array would be 3,8.So find to this pair I listed out my approach where I take the first element and I subtract it with the Total value possible and searching the other element through basic search algorithms.

Using the example here I first take 10 and subtract it with 200 which gives 190,then I search for 190,if it is found then the pair is found otherwise continue the same process.

Answer

If you're trying to find a pair (2) numbers which sum to a third number, in general you'll have something like:

for(i=0;i<N;i++)
   for(j=i+1;j<N;j++)
      if(numbers[i]+numbers[j]==result)
         The answer is <i,j>
         end

which is O(n^2). However, it is possible to do better.

If the list of numbers is sorted (which takes O(n log n) time) then you can try:

for(i=0;i<N;i++)
   binary_search 'numbers[i+1:N]' for result-numbers[i]
   if search succeeds:
      The answer is <i, search_result_index>
      end

That is you can step through each number and then do a binary search on the remaining list for its companion number. This takes O(n log n) time. You may need to implement the search function above yourself as built-in functions may just walk down the list in O(n) time leading to an O(n^2) result.

For both methods, you'll want to check to for the special case that the current number is equal to your result.

Both algorithms use no more space than is taken by the array itself.

Apologies for the coding style, I'm not terribly familiar with Java and it's the ideas here which are important.