Opposite-direction pointers (start/end converging)
corebeginnerTwo pointers start at the two ends of a sorted array or string and move toward each other, comparing or combining the elements they point at — reversing, checking a palindrome, or finding a pair with a target sum, all in one O(n) pass.
Think of it as
left starts at index 0, right starts at the last index. Each step looks at both elements together, decides what to do, and moves at least one pointer inward, shrinking the gap between them. The moment left and right meet or cross, every relevant pair has already been considered exactly once.
What we're doing: Find two numbers in a SORTED array that add up to a target, without a hash map.
- 5
- Because the array is sorted, a total that is too small can ONLY be fixed by moving left inward — every value at or before it is even smaller.
- 7
- Symmetrically, a total that is too big can only be fixed by moving right inward.
[0, 1]
[1, 3]Why this works: For [2, 7, 11, 15], target 9: starting at 2 + 15 = 17 (too big, move right), then 2 + 11 = 13 (too big, move right), then 2 + 7 = 9 — a match at indices [0, 1]. The second call similarly narrows down to indices 1 and 3 (2 + 4 = 6).
Moving the wrong pointer when the sum misses the target
Wrong
Better
What you see: two_sum_sorted_wrong([2, 7, 11, 15], 9) returns [] even though 2 + 7 = 9 is a valid answer at indices 0 and 1.
Why: The branches are swapped: a sum that is too big moves right further down (making it even smaller than needed) instead of moving right inward correctly, and there is no equality check at all — the pointers end up sliding past the answer without ever comparing to it.
- Two Sum II - Input Array Is SortedeasyLeetCode
Exactly the example above — the sorted-array version of Two Sum, in O(1) space instead of a hash map.
- Container With Most WatermediumLeetCode
Start at both ends; always move the pointer at the SHORTER line inward, since the taller one can never be the bottleneck again.
Remember: On a sorted array: sum too small, move left inward; sum too big, move right inward — swapping that rule breaks the search entirely.