The Gateway to Computer Science Excellence
0 votes
12 views
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$.
in Algorithms by Boss (42.5k points) | 12 views

1 Answer

0 votes
Sort the elements - Complexity $\theta\large{(nlogn)}$

Set two pointers, low=array[1] , high=array[n]

 

func(check)

{

while(low!=high)

{

if(array[low]+array[high]>x)

{

high=high-1;

}

else

if(array[low]+array[high]<x)

{

low=low+1;

}

else

return true;

}

return false;

}
by Active (2.4k points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,385 answers
198,542 comments
105,343 users