Two pointers from both ends
🌍 In real life. Two friends check a long shelf of books, sorted by price, for two books that together cost exactly the 500 taka on a gift voucher. One starts at the cheapest book, the other at the dearest. Too expensive together? The one at the dear end steps towards the middle. Too cheap? The one at the cheap end steps in. They never walk past each other, and they never go back.
Two positions moving towards each other through a list are called two pointers. They turn many O(n²) "try every pair" problems into one O(n) walk.
The idea in one sentence: keep two positions, L at the start and R at the end, look at the two items, and use what you see to move one (or both) inward, until they meet.
Its words:
- pointer: here, just a variable holding a position in the list, like
LorR - palindrome: a word that reads the same backwards, like "level"
- sorted: in order from small to big; the pair search needs it to know which pointer to move
First, a palindrome. A word is a palindrome if it reads the same backwards: "racecar", "level". Step by step:
- L = 0, R = last position
- if
word[L] != word[R], it isn't a palindrome: stop - otherwise move both inward:
L += 1,R -= 1 - when L meets or passes R, every pair matched: it is a palindrome
Next, a pair in a sorted list. Given a sorted list, find two numbers that add up to a target. Start with L at the smallest and R at the biggest:
- if
nums[L] + nums[R]equals the target, done - if the sum is too small, the only way to grow it is a bigger left number:
L += 1 - if it is too big, the only way to shrink it is a smaller right number:
R -= 1 - if L meets R, there is no such pair
The list must be sorted: the moves rely on "right means bigger". Watch the search for 13:
What it costs. Every step moves L right or R left (or both), and they start n − 1 apart, so there are at most n − 1 steps: O(n) time and O(1) extra memory, no dict needed. Checking every pair would be n(n − 1)/2 sums. (Lesson 2 shows why skipping all those pairs never misses the answer.)
def is_palindrome(word):
l, r = 0, len(word) - 1
while l < r:
if word[l] != word[r]:
return False
l += 1
r -= 1
return True
def pair_sum(nums, target):
l, r = 0, len(nums) - 1
while l < r:
s = nums[l] + nums[r]
if s == target:
return l, r
if s < target:
l += 1
else:
r -= 1
return None
print(is_palindrome("racecar"), is_palindrome("rocket"))
print(pair_sum([1, 3, 4, 6, 9], 13), pair_sum([1, 3, 4, 6, 9], 2))Mistakes and edge cases.
while l <= rin the pair search would let a number pair with itself; usel < r- on an unsorted list the pair search silently misses answers: sort first (O(n log n)), or use Chapter 35's dict
- real sentences have spaces, capitals and commas: clean them first (
ch.isalnum(),.lower()), then check - an empty word or a single letter is a palindrome: the loop never runs
Quiz
How many letter pairs does the two-pointer check compare for "level"? What does this print?
word = "level" l, r, checks = 0, len(word) - 1, 0 while l < r: checks += 1 if word[l] != word[r]: break l, r = l + 1, r - 1 print(checks)In the sorted pair search, nums[L] + nums[R] is smaller than the target. What should move?
- L moves right, to a bigger number
- R moves left, to a smaller number
- Both move inward
What does this print?
nums = [2, 3, 5, 8] l, r = 0, 3 while l < r and nums[l] + nums[r] != 8: if nums[l] + nums[r] < 8: l += 1 else: r -= 1 print(l, r)Why must the list be sorted for the pair search?
- The moves assume moving right gives a bigger number and moving left a smaller one
- Python can only add sorted numbers
- It isn't needed: two pointers work on any list
What do both two-pointer searches cost on a list of n items?
- O(n) time, O(1) extra memory
- O(n²) time, O(1) extra memory
- O(n) time, O(n) extra memory
pair_sum([1, 3, 4, 6, 9], 13) should give (2, 4), but this answers None. Which line is wrong?
def pair_sum(nums, target): l, r = 0, len(nums) - 1 while l < r: s = nums[l] + nums[r] if s == target: return l, r if s > target: l += 1 else: r -= 1 return None
Coding tasks
Write
is_palindrome(text)with two pointers: ignore everything but letters and digits, and ignore case, so "Was it a car or a cat I saw?" is a palindrome.Write
pair_sum(nums, target)for a sorted list, with two pointers: the positions(l, r)of two numbers that add up totarget, orNone.