Two Pointers
Two indices moving through the data so each step rules work out instead of repeating it.
Presets:
STEP 1/8Place a pointer at each end
−4
−1
2
3
5
7
10
13
Pairs still possible28 / 28
Space Play←→ StepR Replay
1 / 8
PYTHONnums = [−4, −1, 2, 3, 5, 7, 10, 13], target = 8
1def two_sum_sorted(nums, target):
2 left, right = 0, len(nums) - 1
3 while left < right:
4 total = nums[left] + nums[right]
5 if total == target:
6 return [left, right]
7 elif total < target:
8 left += 1
9 else:
10 right -= 1
11 return []
Line 3: loop while the pointers haven’t met. Using < (not <=) stops an element pairing with itself.
STEP 1 OF 8Setup
Place a pointer at each end
left = 0 points at −4, the smallest value; right = 7 points at 13, the largest.
Why it works: Every candidate pair sits between the two pointers - 28 pairs for 8 numbers. Each comparison will rule out a whole group of them.
VARIABLES
Updated- left
- 0
- right
- 7
- nums[left]
- −4
- nums[right]
- 13
- total
- -
- target
- 8
Recognize it
sortedpairin placepalindromeremove duplicates
- n ≤ 10⁵ rules out checking every pair
- O(1) extra space rules out a hash map
Knowledge check 1 of 3
nums = [1, 4, 6, 8, 11] and target = 10. The first check is 1 + 11 = 12. What should happen next?
Practice
Beginner
- Valid PalindromeIgnore case and non-alphanumeric characters, then compare from both ends.LeetCode 125 · 1 ≤ s.length ≤ 2·10⁵ ↗ (opens in a new tab)
- Two Sum II – Input Array Is SortedThe sample above, returning 1-based indices. Exactly one answer exists.LeetCode 167 · 2 ≤ n ≤ 3·10⁴, sorted ↗ (opens in a new tab)
- Squares of a Sorted ArrayNegatives make the largest squares sit at both ends - fill the result from the back.LeetCode 977 · 1 ≤ n ≤ 10⁴ ↗ (opens in a new tab)
Intermediate
- 3SumSort, fix one number, then run two pointers on the rest. Skip duplicates.LeetCode 15 · 3 ≤ n ≤ 3000 ↗ (opens in a new tab)
- Container With Most WaterAlways move the shorter line - the taller one can’t raise the water level.LeetCode 11 · 2 ≤ n ≤ 10⁵ ↗ (opens in a new tab)
- Sort ColorsSort 0s, 1s and 2s in one pass with three pointers (Dutch national flag).LeetCode 75 · 1 ≤ n ≤ 300 ↗ (opens in a new tab)
Advanced
- Trapping Rain WaterTrack the running max from each end and move the side with the lower wall.LeetCode 42 · 1 ≤ n ≤ 2·10⁴ ↗ (opens in a new tab)
- 4SumTwo outer loops plus two pointers, with duplicate skipping at every level.LeetCode 18 · 1 ≤ n ≤ 200 ↗ (opens in a new tab)
- Boats to Save PeopleSort weights and pair the heaviest with the lightest whenever they fit.LeetCode 881 · 1 ≤ n ≤ 5·10⁴ ↗ (opens in a new tab)