I'm trying to clarify how to calculate O(n) for the following case:
Given a sorted array, how would you find two numbers whose sum is equal to a given number x in O(n)?
An O(n) solution would be:
This would be worst case O(n) as you only need a single pass on the array.
An O(n * log n) solution would be:
This is O(n log n) as you would need to run a binary search (log n) at worst n/2 times giving O(n/2 * log n) which in big O is O(n * log n)
Is this correct?
Yep, for both algorithm ur analysis is correct.
Your first algorithm uses O(n) space also, coz of hashmap. U can avoid that.
Algo :
1. Consider begin = 0, and end = last_index
2. Consider data[begin] and data[end]
3. If data[begin] + data[end] > req_sum:
end=end - 1 // u need to decrease ur total sum
elif data[begin] + data[end] < req_sum:
begin = begin + 1 // u need to increase ur total sum
elif data[begin] + data[end] == req_sum:
print("found")
4. Continue from Step 2.
Obviously avoid case where end < begin
and other corner cases .