I have taken algorithms course this semester and I am trying to solve a problem in CLRS
2.3-7
Describe a theta(n lg 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.
I have no idea how to approach this problem.
I am trying to solve it using the merge sort algorithm since it completes in nlogn time, but i dont know if it is the right approach.
Can anyone tell me what is the general approach when solving algorithms when the running time is already specified?
Thanks.
I doubt there is any general approach for such problems, like in any “propose algorithm” tasks. The required runtime, however, can hint on the “building blocks” to use (like presence of
logusually indicates the need for tree or sorted array). You can, for example, look at tag wiki for ‘big-o’ for examples of algorithms for each required runtime.An idea of algorithm for your problem:
First, sort the array (
O(n lg n)); then for each elementyof the array check whether elementx-yis present (alsoO(n lg n), since array is sorted).