The traditional two sum problem (my below reference implementation) is, for a sorted array, find all pairs of numbers which sum value is equal to a given target value. Traditional implementation scans from two ends of array, increase low index pointer if current sum is smaller than target value, decrease high index pointer if current sum is larger than target value.
My question is, is there a proof to show the correctness of this algorithm, showing that it does not miss a pair?
BTW, if my code has issues, please feel free to point out.
def twoSum(numbers, skipIndex, targetValue):
i = 0
j = len(numbers) - 1
result = []
while i < j:
if i in skipIndex:
i+=1
if j in skipIndex:
j+=1
if numbers[i] + numbers[j] == targetValue:
result.append((numbers[i], numbers[j]))
i += 1
j -= 1
elif numbers[i] + numbers[j] > targetValue:
j -= 1
else:
i += 1
return result
if __name__ == "__main__":
numbers = [1,2,4,5,6,7,9,10]
print twoSum(numbers, [1], 11) # output, [(1, 10), (4, 7), (5, 6)]
print twoSum(numbers, [], 11) # output, [(1, 10), (2, 9), (4, 7), (5, 6)]
(5,6)would just be transpositions of values already found. Second, you'll need to prove that the algorithm didn't skip any value-pairs - such proofs usually take the form of "assume there exists ajsuch thati+jis a match.." and then show that it will be included by the algorithm. It might help to first prove that the algorithm finds the value-pairs in sorted order.. - thebjornskipIndexand assume we've proven that the algorithm finds value-pairs in sorted order, then (premise) let's assume there exists a value(a,b), witha<bthat is missing and should have been included between(i0, j0)and(i1, j1). Since the array is sorted and without duplicates, we have thati0 < a < i1(and similarly forb). If (base case)a == i0 + 1then the algorithm would finda,beither in its first iteration afteri0,j0or when testingaagainst values in<a..i1>. (recursive step) If the algorithm has testedi0+nwithout finding the (cont.) - thebjorn