0

I'm learning algorithms and I'm reading the book "introduction to algorithms 3rd edition", and in a problem section it describes the next problem :

Describe a O(n*log(n))-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.

And I don't know if it propose and ordered Set or an unordered Set?

1
  • The set S is initially unordered. Commented Mar 12, 2016 at 3:02

2 Answers 2

2

Let x be the sum you want to have. First sort the array. Then for each element in array (a[i]), find if (x-a[i]) exists in the array using binary search.

The pseudo code :

 sort(a,n)
 for i : 1 to n
     if(binary_search(a,i+1,n-1,x-a[i]))
          return true
 return false

Other method: After sorting, use two pointers first and last to check:

 while(first < last) {
        if(a[first]+a[last] == x) return true;
        else if(a[first]+a[last] < x) first++;
       else if(a[first]+a[last] > x) last--;
    }
    return false;
Sign up to request clarification or add additional context in comments.

3 Comments

I think you want while(first < last) otherwise you'll return true when x/2 appears in the array.
Yes, my bad. Thank you :)
@user3763927 : Would really appreciate if you accept this answer if it works for you.
0

Given a sorted array, you can find if there's a pair that sums to x with with O(n) arithmetic operations.

i := 0
j := len(A) - 1
while i < j {
    if A[i] + A[j] < x {
        i += 1
    } else if A[i] + A[j] == x {
        return true
    } else if A[i] + A[j] > x {
        j -= 1
    }
}
return false

Given this, you can determine if any array contains a pair of elements that sums to x using O(n log n) arithmetic operations by sorting the array, and then using the algorithm above.

1 Comment

Can you please take a look stackoverflow.com/questions/71136657/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.