Length 2:11Two pointers: how it works and when to use it
Two pointers walk a list from both ends, or one behind the other, so a pair search takes one pass. Signals, a worked example, code and practice.
On this page
The video
Container With Most Water
LeetCode 11Open the video page
Chapters
- Play from 0:00Which pair holds the most water
- Play from 0:07How much water fits
- Play from 0:14Trying every pair is slow
- Play from 0:23Start at both ends
- Play from 0:32Always move the shorter wall
- Play from 0:41Walking to the best pair
- Play from 0:51The code in JavaScript
- Play from 1:01Recap: one sweep is enough
Transcript
Show the whole transcriptHide the transcript
- Play from 0:00
Here is a row of walls with different heights.
- Play from 0:02
Pick two and fill the space between them with water.
- Play from 0:05
Which pair holds the most?
- Play from 0:08
Water spills over the shorter wall.
- Play from 0:10
So the amount is the shorter height times the distance between the walls.
- Play from 0:15
Trying every pair works, but nine walls already make thirty six pairs, and the count grows with the square of the number of walls.
- Play from 0:23
Instead, start with one pointer on the first wall and one on the last.
- Play from 0:27
This widest container is one unit high and eight wide, so it holds eight.
- Play from 0:33
Moving the pointer at the taller wall can never help.
- Play from 0:36
The width shrinks, and the water stays below the short wall.
- Play from 0:39
So the shorter side steps inward.
- Play from 0:42
Repeat until the pointers meet, keeping the best area.
- Play from 0:45
The winning walls are eight and seven high, seven apart, so they hold forty nine units.
- Play from 0:52
In JavaScript, that is one while loop.
- Play from 0:54
Each pass works out the area, keeps the best, and steps the shorter side in.
- Play from 0:58
On our row, it prints forty nine.
- Play from 1:01
So nine walls take eight checks instead of thirty six.
- Play from 1:05
Always move the shorter wall, and one sweep finds the biggest container.
Two pointers means keeping two positions in a list and moving them by a rule. A pointer here means a position in the list, like "index 3". Often one starts at each end and they walk toward each other. Each step, a simple fact tells you which one can move without missing the answer. When they meet, you're done. That turns a search over every pair into a single pass.
The idea in one minute
Many problems ask you to find the best pair, or a pair that meets a rule. The slow way checks every pair. A list of 9 items has 36 pairs. A list of 10,000 items has almost 50 million.
With two pointers, you start with one pair and throw away one item at every step. You only throw away an item when you can prove it can't be part of a better answer. After about n steps, every item has been dealt with.
There are two common shapes:
- From both ends.
leftstarts at the first item andrightat the last. They move toward each other until they meet. This fits sorted lists, palindromes, and problems like the water container below. - One behind the other. Both start at the front. A fast pointer reads every item. A slow pointer marks where the next item you keep should go. This fits "remove these items in place" problems.
When to use it
Look for these signals:
- The input is a list or a string, and you're looking for a pair, or comparing the two ends.
- The list is sorted, or sorting it first doesn't break the problem. Sorted order is what lets you decide which pointer to move.
- At each step, you can name the item that can't help any more.
- The problem says in place, meaning you must change the list itself without making a copy.
If you need the original positions of a pair in an unsorted list, sorting would scramble them. A hash map, a lookup table from each value to its position, is usually the better tool then.
A worked example
This is the example from the video. It is LeetCode 11, Container With Most Water. In our words: you have a row of walls of different heights. Pick two walls and fill the space between them with water. Which pair holds the most?
Water spills over the shorter wall. So the amount is the shorter height times the distance between the walls.
Our walls are [1, 8, 6, 2, 5, 4, 8, 3, 7], at positions 0 to 8.
We start with the widest container: the first wall and the last. Then, each step, we work out the area, keep the best, and move the pointer at the shorter wall inward.
| left | right | heights | width | area | best | move |
|---|---|---|---|---|---|---|
| 0 | 8 | 1 and 7 | 8 | 8 | 8 | left |
| 1 | 8 | 8 and 7 | 7 | 49 | 49 | right |
| 1 | 7 | 8 and 3 | 6 | 18 | 49 | right |
| 1 | 6 | 8 and 8 | 5 | 40 | 49 | left |
| 2 | 6 | 6 and 8 | 4 | 24 | 49 | left |
| 3 | 6 | 2 and 8 | 3 | 6 | 49 | left |
| 4 | 6 | 5 and 8 | 2 | 10 | 49 | left |
| 5 | 6 | 4 and 8 | 1 | 4 | 49 | left |
The pointers meet after 8 steps. The best pair is the walls at positions 1 and 8, heights 8 and 7, which are 7 apart. They hold 7 times 7, which is 49.
When both walls are the same height, as in row 4, it doesn't matter which one moves. Neither can be part of a bigger container with a closer wall.
Why moving the shorter wall is safe
Say the left wall is the shorter one. Now pair it with any wall closer than right. The width gets smaller. The water level is set by the shorter of the two walls, so it can never be higher than the left wall. So every other container that uses the left wall holds no more than the one we just measured.
We already measured the best container the left wall can make. We can drop it. Moving the taller wall instead would throw away pairs that might be better.
The code in JavaScript
function maxArea(height) {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const h = Math.min(height[left], height[right]);
best = Math.max(best, h * (right - left));
if (height[left] <= height[right]) left++; // the shorter side moves
else right--;
}
return best;
}
maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]); // 49
From both ends, in a sorted list
Find two numbers in a sorted list that add up to a target. If the sum is too small, the only way to grow it is to move left up. If it's too big, move right down.
function pairWithSum(sorted, target) {
let left = 0;
let right = sorted.length - 1;
while (left < right) {
const sum = sorted[left] + sorted[right];
if (sum === target) return [left, right];
if (sum < target) left++; // need a bigger sum
else right--; // need a smaller sum
}
return null; // no pair adds up to target
}
pairWithSum([1, 3, 4, 6, 8, 11], 10); // [2, 3], because 4 + 6 = 10
One behind the other
Remove every copy of a value from a list, in place, and return how many items are left. read looks at every item. write marks where the next kept item goes.
function removeAll(nums, value) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== value) {
nums[write] = nums[read];
write++;
}
}
return write; // the first `write` items are the ones we kept
}
removeAll([3, 1, 3, 2, 3], 3); // 2, and the list now starts with 1, 2
How fast is it?
Programmers describe speed with Big-O notation. It says how the work grows as the input grows. O(n) means the work grows in step with n, the number of items. O(n²) means it grows with the square: double the list, and the work goes up four times.
- Time: O(n). Each step moves one pointer by one place, and the pointers never move back. So there are at most
nsteps. Checking every pair instead takes O(n²). - Memory: O(1). You only keep a few numbers, however long the list is.
- If you sort first, sorting costs O(n log n). That is a little more than O(n), and much less than O(n²). The binary search guide explains what "log n" means.
For the 9 walls in the example, that is 8 steps instead of 36 pairs.
Common mistakes
- Moving the taller wall. It feels natural to keep the tall wall, but the rule is the other way round. The shorter wall is the one that can't do better.
- Using
left <= right. A pair needs two different items. With<=, the loop also tries an item paired with itself. - Forgetting that the width is
right - left. There is no+ 1here. You count the gaps between walls, not the walls. - Running a sorted-list method on unsorted input.
pairWithSumonly works because the list is sorted. Sort it first, or use a hash map if the original positions matter. - Repeating answers in 3Sum style problems. When the same number appears twice in a row, skip the copies, or you'll report the same triple more than once.
- Changing the list while you still need the old values. In the "one behind the other" shape,
writenever passesread, so you never overwrite an item you haven't read yet. Keep it that way.
Practice problems
- LeetCode 125, Valid Palindrome. From both ends. Skip anything that isn't a letter or a digit.
- LeetCode 167, Two Sum II - Input Array Is Sorted. The
pairWithSumidea. Watch how positions are counted in the answer. - LeetCode 26, Remove Duplicates from Sorted Array. One behind the other.
- LeetCode 283, Move Zeroes. One behind the other, keeping the order of the other numbers.
- LeetCode 15, 3Sum. Fix one number, then run two pointers on the rest. Skip repeats.
- LeetCode 42, Trapping Rain Water. A harder cousin of the water container, with a different rule for which side moves.
In short
Two pointers keeps two positions and moves one of them each step. The trick is a reason to throw away one item at every step. For the water container, the shorter wall is always the one to drop, so one sweep finds the biggest container.
Want a video for a different problem?
Type a problem, a pattern or a system to design. You get a narrated video like the one above, usually ready in 5 to 9 minutes.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video