Two Pointers (Converging)
Use on sorted arrays to find pairs. The foundational technique for iterating arrays with two indices.
Recognition
- Array/string is sorted or can be processed from both ends.
- You need a pair/triple whose sum or difference meets a target.
- You can discard one side after comparing the current pair.
When not to use it
Do not use converging pointers on unsorted pair-sum problems without sorting or hashing first.
Do not advance both pointers after every comparison.
Logic template
Python
def two_pointers(nums, target):
l, r = 0, len(nums) - 1
while l < r:
total = nums[l] + nums[r]
if total == target:
return [l, r]
elif total < target:
l += 1
else:
r -= 1
return []JavaScript
function twoPointers(nums, target) {
let l = 0, r = nums.length - 1;
while (l < r) {
const total = nums[l] + nums[r];
if (total === target) return [l, r];
else if (total < target) l++;
else r--;
}
return [];
}O(N) after sorting when needed; O(1) extra space for the classic converging form.
- Everything outside [l, r] has already been considered and can be ignored.
- The current pair is the next best candidate under the ordering constraint.
Worked example
Two Sum II on a sorted array
nums = [2, 7, 11, 15], target = 9
- Start with l=0 (2) and r=3 (15). Sum=17 is too large, so move r left.
- Now l=0 (2), r=2 (11). Sum=13 is still too large, so move r left again.
- Now l=0 (2), r=1 (7). Sum=9 matches the target.
- Return the 1-indexed pair [1, 2].
Result: [1, 2]
Common pitfalls
- Forgetting to skip duplicates in multi-sum variants.
- Using <= instead of < and revisiting the same index.
- Sorting when relative indices matter and the problem forbids it.