I have thought about the most useful way of checking an array for 2 elements that sum to X. The trivial solution is to check the sum of every element with every element, and the complexity of this solution is $O(n^2)$.
My solution is: Say the array is A. It's length is N. Elements are from A[0] to A[N-1]
Pseudo-Code is:
Check_Sum(A,left,right) {
mid <-- floor( (left+right)/2 )
if(A[left]+A[right]=X)
return true
return Check_Sum(A,left,mid)||Check_Sum(A,mid,Right)
}
My question is: Is the complexity of my solution equal to $O(n \lg n)$?
[1, 4, 5, 7]
to see if two elements sum to9
. Your algorithm will try1+7
, then1+4
, then5+7
(ignoring the bugs that prevent it from even doing that). Hint: you can sort the entire array in $O(n\log n)$, at which point solving this problem is easy. $\endgroup$