I have been solving the problem of two sum with a sorted array, which can described as follows:
Given a sorted array
arr
sorted in non-decreasing order and a targettarget
, find whether two indicesi
andj
exist such thatarr[i] + arr[j] == target
. The solution must use constant extra space.
The optimal solution to this problem involves using two pointers, left
and right
set to 0
and len(arr) - 1
respectively for either end of the array. While left < right
, the sum of the elements at each respective pointer is checked. If said sum is less than the target sum, the left pointer is incremented. If the sum is greater than the target, the right pointer is decremented. If the sum equals the target, we return true
. At the end of the function, we return false
otherwise since no such pair was found.
What I'm struggling with is to understand why this is correct. I see that decrementing right
when the sum is too big will reduce the sum, but I don't see why decrementing left
would also not decrease the sum. Likewise, if the sum is too small, incrementing right
would increase the sum just as much as incrementing right
. I tried to construct a proof by contradiction for the latter case:
Incomplete proof:
Given two indices $l$ and $r$ in an array $A$ sorted in non-decreasing order and a target sum $t$, where $l < r$ and $A[l] + A[r] < t$, let us assume that there exists some index $r'$ such that $r' > r$ and $A[l] + A[r'] == t$.
Then, since $A[l] + A[r] < t$ and $A[l] + A[r'] == t$, we can state that $A[l] + A[r] < A[l] + A[r']$. From this, it follows that $A[r] < A[r']$
It's at this point I'm not sure where to go. The goal is to disprove the existence of some $r'$, because that would show that incrementing the right pointer is not the correct way to reach the target sum. I'd imagine that I could use a similar proof for decrementing the left pointer when the sum is too high as well. What would be the best way to continue this proof/fix any errors in my assumptions?