edited by
995 views
5 votes
5 votes

Let $A$ be an array of $n$ integers, sorted, so that $A[1] \leq A[2] \leq \dots A[n]$. Suppose you are given a number $x$ and you wish to find out if there are indices $k$ and $l$ such that $A[k]+A[l] = x$.

  1. Design an $O(n \log n)$ time algorithm for this problem.
edited by

1 Answer

Best answer
17 votes
17 votes

a.  Pseudo code for time complexity $O(n\log n)$ :

for(i=1; i<=n; i++)
{
    if (binary_search( x- A[i] ) // O(logn)
    return true;
}
return false;

 

b. Pseudo code for time complexity $O(n)$ :

for( k=1, l=n; k<l ; )
{
    temp =A[k] + A[l];
    if (temp== x)
        return true;
    else if(temp > x)
        l--;
    else
        k++;
}
return false;

 

edited by

Related questions

12 votes
12 votes
4 answers
1
go_editor asked May 27, 2016
1,492 views
Let $A$ be an array of $n$ integers, sorted so that $A \leq A \leq \dots A[n]$. Suppose you are given a number $x$ and you wish to find out if there exist indices $k$ a...