From absolute beginner to advanced — interactive lesson with live examples
Two pointers works because the array is sorted. This gives us a superpower:
So when our sum is too small, we know exactly what to do — move left pointer right to get a bigger number. When too big, move right pointer left. We never need to backtrack or check everything.
arr = [2, 5, 8, 11, 14] target = 13
Initial: L=0(2) R=4(14)
[2, 5, 8, 11, 14]
L R
Step 1: 2 + 14 = 16 > 13 TOO BIG → R moves left
[2, 5, 8, 11, 14]
L R
Step 2: 2 + 11 = 13 = 13 MATCH ✅ → return [0, 3]
[2, 5, 8, 11, 14]
L R
| # | Problem | Difficulty | Key learning |
|---|---|---|---|
| 167 | Two Sum II | Easy | Classic template — start here |
| 125 | Valid Palindrome | Easy | Both pointers move inward checking chars |
| 15 | 3Sum | Medium | Fix one element, two pointers on the rest |
| 11 | Container With Most Water | Medium | Maximise area by moving shorter side |
| 42 | Trapping Rain Water | Hard | Track max height from both sides |
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right] # found answer
elif current_sum < target:
left += 1 # need bigger — go right
else:
right -= 1 # need smaller — go left
return [-1, -1] # no pair found