I recently came across a solution for the subarray sum problem with two pointers and I'm not really sure about the correctness of the algorithm. The subarray sum problem consists of finding a subarray whose sum is equal to some target value. I've seen solutions of this problem using a hash table but I question the correctness of this other solution. Let me give you guys an example of the algorithm.
Suppose you have an array [1,3,2,5,1,1,2,3] and a target value x = 8.
Use left and right pointers that indicate the beginning and end of the subarray. On each step the left pointer moves one step forward and the right pointer moves forward as long as the subarray sum is at most x. This is how the algorithm will progress for the above array.
[1,3,2,5,1,1,2,3]
l r
[1,3,2,5,1,1,2,3] ##The right pointer doesn't move because the next element would make the sum larger than x
l r
[1,3,2,5,1,1,2,3]
l r
The sum is now equal to the target and the algorithm ceases. To me the algorithm doesn't seem to be valid for edge cases. But it looks right for every test case i give it and it runs O(n). Can someone give me a proof of correctness on this?
Thanks
edit - For the sake of argument assume positive integers.
To me the algorithm doesn't seem to be valid for edge cases.What are those edge cases? - Shridhar R Kulkarni