Lesson 1 of 4
Two pointers from both ends
Put one index at each end of a list or string and walk them toward each other. Every step proves that one item cannot be part of a better answer, so problems that seem to need every pair take one pass.
Trace two pointers moving inward and say where they stop on odd and even lengths
Check a palindrome by comparing mirror pairs and skipping characters that do not count
Solve two sum on a sorted list in O(n) time and O(1) extra space, and say why each pointer move is safe
Find the two walls that hold the most water by always moving the shorter wall
Solve three sum by sorting, fixing one number, and skipping repeated values
Does "reader" read the same backwards? You would not copy it out in reverse. You would put one finger on the first letter and one on the last, check that they match, and slide both fingers one letter toward the middle. Then again, until the fingers meet or a pair disagrees. Two fingers closing in from the ends is the whole pattern of this lesson.
The same two fingers solve harder problems. On a sorted list of prices, they find two prices that add up to a gift card's value. On a row of walls, they find the two walls that hold the most water. Each of these seems to need every pair, which is O(n2) work, and each one takes a single walk inward, O(n). (O(n) means the work grows in step with the length n; O(n2) means it grows like n times n.)
What makes it work is one question, asked at every step: which finger can move without losing the answer? Each section below answers it for one problem.
Two fingers on a word
How do you compare a word with its reverse without building the reversed copy? Compare mirror pairs: the first character with the last, the second with the second to last, and so on. Each comparison needs two positions, so we keep two indexes. An index that we move along the data is called a pointer. left starts at position 0 and right at the last position, len(word) - 1. (Positions count from 0, so a five-letter word has positions 0 to 4.)
The trace runs the check on two words: "radar", a palindrome (a word that reads the same both ways), and "reader", which is not. The two arrows under the word are the pointers. Before you step through, guess how many pairs each call compares.
def is_mirror(word):left = 0right = len(word) - 1while left < right:if word[left] != word[right]:return Falseleft += 1right -= 1return Trueprint(is_mirror("radar"), is_mirror("reader"))
(nothing printed yet)The loop runs while left < right, that is, while the pointers sit on two different positions. On an odd length they meet on the middle character, which is its own mirror and needs no check. On an even length they step past each other. Either way, when no pair disagrees, every mirror pair is compared exactly once. A mismatch ends the walk at once, because one disagreeing pair is enough to say no.
This loop moves the pointers exactly as is_mirror does when every pair matches, but compares nothing. Type exactly what it prints, one line per word.
for word in ["kayak", "noon"]:
left = 0
right = len(word) - 1
while left < right:
left += 1
right -= 1
print(word, left, right)
The same walk can write instead of compare. Swap each mirror pair, and the list ends up reversed in place: the list itself changes, and no copy is made. Python swaps two values with a, b = b, a, which works because the right side is built from the old values before either name changes.
Put the lines in order to build reverse_in_place(items), which reverses items by changing the list itself and returns nothing. It is the mirror walk, with a swap where the comparison was. Indentation is part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
left, right = left + 1, right - 1left, right = 0, len(items) - 1def reverse_in_place(items):while left < right:left, right = right, leftitems[left], items[right] = items[right], items[left]items[left] = items[right]
Now a real problem. Real text has spaces, commas and capital letters, and the problem says those do not count: "No, on" is a palindrome because its letters, in lowercase, are noon. Two string methods from module 1 do the work for one character c: c.isalnum() is True when c is a letter or a digit, and c.lower() gives the lowercase version.
Each pass of the loop now makes one decision. Call the text s. If s[left] does not count, move left past it. Otherwise, if s[right] does not count, move right past it. Otherwise compare the two characters in lowercase. A skip moves one pointer; a match moves both, because a skipped character sits on one side only, while a matched pair has one character on each side.
The pointers never build a cleaned copy. Cleaning the string and reversing it is also O(n) time, but it builds two new copies of up to n characters each, the cleaned text and its reverse; the pointers store two integers. The trap is isalpha(), which is True only for letters: it would skip digits and call "a1a2" a palindrome.
So far: two pointers start at the two ends and move inward while left < right. Every pass moves at least one pointer one place closer to the other, so the walk is O(n).
Sorted two sum: which pointer moves
In the mirror walk both pointers moved together. Here only one pointer moves per step, and the sum decides which. You have a list of prices sorted from cheapest to most expensive, and a gift card worth 10. Which two prices add up to exactly 10?
The brute force (the plain method that tries everything) checks every pair of positions: O(n2). Module 3's two sum did better with a dict: for each number x, look up its partner target - x among the numbers already passed. That is O(n) time but O(n) extra space, and it ignores what this list gives us: it is sorted.
Put left on the cheapest price and right on the most expensive, and add the two. The prices from left to right are the ones still in play: not yet ruled out.
- Too small:
nums[right]is the biggest price still in play, and even it is not enough fornums[left]. Every other partner is the same or smaller. Sonums[left]is in no answer: moveleftup one. - Too big: by the mirror argument,
nums[left]is the smallest price still in play, and even it overshoots withnums[right]. Sonums[right]is in no answer: moverightdown one. - Equal: done.
A pointer only moves past a number we have proved cannot be in the answer. That is why each move is safe: a sum that is too small drops the smaller number, and a sum that is too big drops the bigger one. Before you step through, guess the two prices in [1, 3, 4, 6, 8, 11] that use a card worth 10, and how many sums the walk computes to find them.
def pick_two(nums, target):left = 0right = len(nums) - 1while left < right:total = nums[left] + nums[right]if total == target:return [nums[left], nums[right]]if total < target:left += 1else:right -= 1return None
(nothing printed yet)Each sum either finds the pair or rules out one number for good. Six numbers start five places apart, so the walk computes at most five sums; this one needed all five. Compare that with the brute force:
The brute force for this question tries every pair of different positions. How many pairs does a list of 6 numbers have? (Count each pair once: positions 0 and 1 are the same pair as 1 and 0.)
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Check the rule on a new list before you write it.
nums = [2, 4, 7, 9, 13], target = 17. The pointers start at the ends: nums[0] + nums[4] is 2 + 13 = 15, below the target. What should happen next?
Choose one answer, then check.
The problem asks for the two positions instead of the two prices, and promises that exactly one pair exists. The walk is the same; only the return changes, to [left, right].
Interviewers like to change a known problem to see whether you understand the argument or only remember the code. Here is such a change: count the pairs whose sum is below the target. A too-small sum now settles more than one pair at once.
Write count_below(nums, target). nums is sorted from smallest to largest. Return how many pairs of different positions i < j have nums[i] + nums[j] < target. For [1, 2, 4, 5, 8] and target 7 the answer is 4: 1 + 2, 1 + 4, 1 + 5 and 2 + 4.
Use one walk from both ends. The tests include a list of 15,000 numbers, where trying every pair is too slow.
raise NotImplementedError, then press Run tests. Each check says what it expects.So far: in a sorted list, the sum of the two ends says which end is useless. Too small drops the left number; too big drops the right one. Each sum settles every pair that uses the dropped number, which is how one walk replaces the n(n − 1)/2 checks of the brute force.
Container with most water: move the shorter wall
Now we measure something other than a sum. A row of walls stands on flat ground, one unit apart. Pick two, and water fills the space between them up to the shorter wall, because above that it spills over. The amount is the width times the shorter height: (right - left) * min(heights[left], heights[right]). The walls between the two you pick do not count: ignore them. Which two walls hold the most?
Start with the widest pair, the two ends, and measure it. Now one wall has to go, and the question is which one can go without losing a better answer. Say the left wall is the shorter. Pair it with any other wall between the pointers: the width shrinks, and the water can never rise above the left wall, because the shorter wall sets the level. So every pair the left wall could still make holds no more than the pair we measured. It has nothing left to offer. Always move the pointer at the shorter wall.
The taller wall has no such cap: it might pair with a tall wall further in. Before you step through, guess which two of the walls [2, 7, 3, 8, 4, 5] hold the most.
def max_water(heights):left = 0right = len(heights) - 1best = 0while left < right:water = (right - left) * min(heights[left], heights[right])best = max(best, water)if heights[left] < heights[right]:left += 1else:right -= 1return best
(nothing printed yet)Now do one by hand, one table row per measurement.
Run the shorter-wall walk on paper for heights = [3, 9, 4, 8, 2]. Make a table with the columns left, right, width, shorter wall, water and best, one row per measurement, and write which pointer moves after each row. What is best at the end?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now the full problem. Its examples use new walls; the walk is the one you did by hand.
Ties do not need a rule of their own. When both walls have the same height, each one is "the shorter wall", so the argument lets either go; the solution moves right. best starts at 0, which is the right answer when every wall has height 0.
So far: each step measures one pair, then drops the one wall that has nothing better to offer. The sorted two sum walk drops a number that cannot reach the target; this walk drops a wall that cannot beat best. Same shape, different proof.
Three sum: fix one number, then two pointers
Three sum asks for every triple (a group of three values, from three different positions) that adds up to 0, with each triple listed once. Three nested loops try every triple of positions: about 166 million of them for 1,000 numbers. That is O(n3): the work grows like n times n times n.
Fix one number, and the rest is two sum. If the smallest number of the triple is nums[i], the other two must add up to -nums[i]. Sort the list first, and that is sorted two sum on the positions after i: left = i + 1, right at the last position, and the same moves, now testing whether the total of all three is below or above 0. range(len(nums) - 2) stops i while two positions remain after it, one for left and one for right.
Two things change from sorted two sum. One i can have several triples, so a match records the triple, moves both pointers, and keeps walking. Moving both is safe: any other partner for nums[left] would have to equal nums[right], which gives the same triple again, and the same holds for nums[right]. And each triple must appear once, even when values repeat. Sorting puts equal values next to each other, so a repeat always sits beside another copy, and two skips handle it:
- Skip a repeated smallest number. If
nums[i] == nums[i - 1], the pass for the first copy of this value already searched every position afteri, and more. So this pass could only find triples already recorded, andcontinuemoves on to the nexti. - Skip a repeated middle number after a match. Move
leftpast every copy of the value that matched.
The trace runs on [2, -2, 0, 2, -2, 0], which holds two copies of each value. Guess first: how many triples does it record?
def three_sum(nums):nums = sorted(nums)triples = []for i in range(len(nums) - 2):if i > 0 and nums[i] == nums[i - 1]:continueleft = i + 1right = len(nums) - 1while left < right:total = nums[i] + nums[left] + nums[right]if total < 0:left += 1elif total > 0:right -= 1else:triples.append([nums[i], nums[left], nums[right]])left += 1right -= 1while left < right and nums[left] == nums[left - 1]:left += 1return triples
(nothing printed yet)This is the outer loop of three sum on a sorted list, with the two-pointer walk left out. Type exactly what it prints.
nums = [-3, -3, -1, -1, -1, 2]
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
print(i, nums[i])
Now write it yourself. The problem's examples add a case the trace did not have: one triple that uses two copies of the same value.
right needs no skip of its own. Once left holds a bigger value, the old right value makes the total too big, and the normal rule moves right. And with fewer than three numbers, range(len(nums) - 2) is empty, so the answer is [].
The pattern, and when to reach for it
All four walks share one frame. What changes from problem to problem is the proof that lets a pointer move.
Reach for this pattern when the input is sorted, or sorting is cheap next to the rest of the work, and the question is about pairs. Sorting costs O(n log n), so it adds nothing to the Big O of an O(n2) answer like three sum. Some walks need no sorting at all: mirror questions (palindromes, reversing) get their proof from the mirror, and the container gets it from the shorter wall. If the list is not sorted and you need the original positions, the two sum dict is usually the better tool.
The module's practice bank has one more in this family: Squares of a sorted list, where the biggest square always comes from one of the two ends.
Last, say it the way you would in the room.
An interviewer gives you container with most water. Explain your plan as you would say it before typing: the brute force and its cost, then the walk, the notebook, the promise and the cost of the two-pointer version. Include why it is safe to move the shorter wall.
Saved in this browser as you type.