Two Sum II – Two Pointer Approach (Short Blog)
Problem
Given a sorted array numbers and a target, find two indices such that:
numbers[i] + numbers[j] = target
Return 1-based indices.
Code
class Solution:
def twoSum(self, numbers, target):
l = 0
r = len(numbers) - 1
while l < r:
s = numbers[l] + numbers[r]
if s > target:
r -= 1
elif s < target:
l += 1
else:
return [l + 1, r + 1]
Why This Approach?
- Array is sorted → we can avoid hash maps Use two pointers instead of nested loops
- More efficient → O(n) time, O(1) space
Line-by-Line Idea
l = 0 → start (smallest value)
r = len(numbers)-1 → end (largest value)
while l < r → ensure two different elements
s = numbers[l] + numbers[r] → check current pair
Conditions:
If s > target → decrease sum → r -= 1
If s < target → increase sum → l += 1
If equal → return answer
Key Logic
Because the array is sorted:
Move right pointer left → reduce sum
Move left pointer right → increase sum
Example
numbers = [2, 7, 11, 15], target = 9
Steps:
2 + 15 → too big → move r
2 + 11 → too big → move r
2 + 7 → correct
Output:
[1, 2]
Why It’s Better?
- No extra space (no dictionary)
- Faster than brute force
- Uses sorted property effectively
Top comments (0)