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 is 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 is ensure two different elements
s = numbers[l] + numbers[r] it check current pair
Conditions:
If s > target it decrease sum --> r -= 1
If s < target it increase sum --> l += 1
If equal is return answer
Key Logic
Because the array is sorted:
Move right pointer left is reduce sum
Move left pointer right is increase sum
Example
numbers = [2, 7, 11, 15], target = 9
Steps:
2 + 15 istoo big that move r
2 + 11 is too big that move r
2 + 7 is correct
Output:
[1, 2]
Why It’s Better?
- No extra space (no dictionary)
- Faster than brute force
- Uses sorted property effectively
Top comments (0)