Alex Rivera | Logout

How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

Asked 2010-04-19T10:38:02.250
25

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

Edit
Report

1 Answer

10

Let us say that we want to find two numbers in the array A that when added together equal N.

  1. Sort the array.
  2. Find the largest number in the array that is less than N/2. Set the index of that number as lower.
  3. Initialize upper to be lower + 1.
  4. Set sum = A[lower] + A[upper].
  5. If sum == N, done.
  6. If sum < N, increment upper.
  7. If sum > N, decrement lower.
  8. If either lower or upper is outside the array, done without any matches.
  9. Go back to 4.

The sort can be done in O(n log n). The search is done in linear time.

answered 2010-04-19T10:59:22.770

Your Answer