I recently came across an interesting Java Algorithm statement
Given an array int[] arr{} and a number x, find if there are any 2 numbers in the array whose sum is equal to x.
Hint: Solve it in 3 ways with the following complexities O(n^2), O(n log n) and O(n)
O(n^2) approach is a simple brute force logic. O(n log n) possibly involves merge sorting and using a binary search - though I am able to exactly figure out how to fit in binary search here. I am totally clueless about O(n) algorithm.
Simple Brute force logic:
for(i = 0; i < arr.length; i++){
for(j=0; j<arr.length; j++){
if(arr[i] + arr[j] == x){
return x;
}
}
}
Any pointers?