Two pointers: why one pass is enough
1 Two loops, or two pointers
We have a sorted array and a target. We want two values, at different indexes, that add up to the target:
The first code most of us write tries every pair. An outer loop picks the left value, and an inner loop tries every value after it. Six values make 15 pairs. At n = 10⁵ there are about 5 × 10⁹ pairs. At about 10⁸ steps a second, that is far past the time limit, so it gets Time Limit Exceeded (TLE).
The two loops never use the fact that the array is sorted. Two indexes can. They are the pointers: l starts at the smallest value and r at the largest. We add the two values and compare the total with the target:
- Too small. Move
lone step right, to a bigger value. - Too big. Move
rone step left, to a smaller value. - Equal. We have the pair.
The rule feels right. But when r leaves 11, it never comes back. The pairs 3 + 11, 4 + 11 and the rest are never checked. The next two sections show why none of them could be the answer.
2 Every pair in one grid
To see what a move skips, we write every pair in a grid, like an addition table. The row is the left value and the column is the right value. Each cell holds their sum. A pair needs two different indexes, and 4 + 6 is the same pair as 6 + 4, so only the cells above the diagonal count. The orange row along the top holds the right values, and the orange column down the side holds the left values.
Because the array is sorted, the grid is sorted too:
- Along a row, sums grow to the right. The left value stays the same, and the right value grows.
- Down a column, sums grow downwards. The right value stays the same, and the left value grows.
The two loops read all 15 cells, row by row. Two pointers start at the top-right corner instead, the cell 1 + 11 = 12.
3 Each move crosses out a whole line
The corner cell is the biggest in its row, because every cell to its left has a smaller right value. It is also the smallest in its column, because every cell below it has a bigger left value. So one comparison tells us about a whole line:
- Too big. The corner is the smallest in its column, so every cell in that column is too big. We cross out the column. In the array,
rmoves left. - Too small. The corner is the biggest in its row, so every cell in that row is too small. We cross out the row. In the array,
lmoves right.
After either move, the cells that are left form a smaller grid of the same shape. Its top-right corner is the next pair the pointers check.
Every crossed cell sat in a line that could not hold 10. So the pass never skips the answer. It only skips cells that are sure to be wrong.
The pointers start n − 1 places apart, and each move brings them one place closer. So after at most n − 1 moves they meet. By then every line is crossed out, and if no pair matched, no pair adds up to the target.
4 The trace, the code and the cost
The steps above as a trace table:
| step | l | r | nums[l] | nums[r] | total | move |
|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 1 | 11 | 12 | too big, r left |
| 2 | 0 | 4 | 1 | 8 | 9 | too small, l right |
| 3 | 1 | 4 | 3 | 8 | 11 | too big, r left |
| 4 | 1 | 3 | 3 | 6 | 9 | too small, l right |
| 5 | 2 | 3 | 4 | 6 | 10 | found |
The pointers take turns here, but they do not have to. At each step, the total decides which one moves. The loop runs while l < r, and it returns the two indexes, or [-1, -1] when no pair adds up to the target.
On our array, every tab returns [2, 3] for target 10 and [-1, -1] for target 13.
The loop runs at most n − 1 times, so the search is O(n). At n = 10⁵ that is 10⁵ steps instead of 5 × 10⁹. It uses two indexes and nothing else, so the extra space is O(1). An unsorted array must be sorted first, which costs O(n log n) and then outweighs the pass:
| Way | Time | Extra space | Needs sorted input |
|---|---|---|---|
| Two loops | O(n²) | O(1) | no |
| A hash map of values seen | O(n) | O(n) | no |
| Two pointers | O(n) | O(1) | yes |
| Sort, then two pointers | O(n log n) | O(1) to O(n), for the sort | no |
5 Every pair once, and three values
Some problems want every pair that makes the target, each pair of values once. Two things change after a match:
- Both pointers move. On the grid, the match is the corner. The rest of its row is smaller and the rest of its column is bigger, so both lines are done.
- Repeated values are skipped. If the next value is the same, it would build the same pair again. After a match,
lmoves past every copy of its value, andrdoes the same.
Here is the run on [1, 2, 2, 3, 3, 4] with target 5:
| l | r | total | what happens |
|---|---|---|---|
| 0 | 5 | 5 | keep 1 + 4; both move |
| 1 | 4 | 5 | keep 2 + 3; both move, and l skips the second 2 |
| 3 | 3 | l has reached r, so we stop |
Without the skip, l = 2 and r = 3 would keep 2 + 3 a second time.
Three values that add to a target work the same way. We fix the first value, nums[i], and run the pair search on the part after i, with the target reduced by nums[i]. That is n passes of O(n) each, so O(n²), where three loops would be O(n³). The fixed value needs the skip too. When nums[i] equals nums[i - 1], every triple it could start was already found. Four values fix two, for O(n³).
6 The best pair: move the shorter wall
Some problems have no target. They want the best pair. In one well-known example, walls of different heights stand in a row. Two walls hold water between them, as high as the shorter wall and as wide as the gap. We want the most water.
Again the pointers start at the two ends, the widest pair. Now the rule is to move the shorter wall inwards. The reason is a line of the grid again:
- The wall of height 3 has found its best. The water can never rise above 3 while this wall is in the pair. Every other partner is closer than the right end, so it holds less than 3 × 5. The wall's whole row is crossed out, and
lmoves. - Moving the taller wall proves nothing. Its column is not done. The walls of height 7 and 4 hold 4 × 4 = 16, more than 15, so crossing it out could throw away the best pair.
On these walls the run checks 15, then 16 with heights 7 and 4, then 18 with heights 7 and 6, then two smaller ones. It checks five pairs instead of 15, and 18 is the best.
7 Pointers that move the same way
Not every two-pointer problem starts at both ends. Some ask us to rearrange an array in place, without a second array. Then both pointers start on the left. The read pointer visits every value once. The write pointer marks where the next value we keep goes.
Here we remove the repeats from the sorted [1, 1, 2, 2, 2, 3]. We keep a value when it differs from the last value we kept, the one just before write. Blue is the part we have kept, and orange is a value just written:
The first three places now hold 1, 2 and 3. What is left after them does not matter. The read pointer visits each value once, so this is O(n) time and O(1) extra space.
The write pointer never gets ahead of the read pointer. So a write only lands on a value that was already read. The Sliding Window topic next also moves two pointers the same way, but there everything between them matters.
8 Mistakes, and when to use it
- An unsorted array. The grid is sorted only when the array is. On
[3, 1, 6, 2]with target 9, the pointers report no pair, but 3 + 6 = 9. while (l <= r). Whenlequalsr, the pair is one value used twice, a cell on the diagonal. On[1, 5, 8]with target 10, this gives[1, 1], though no pair exists.- Not moving after a match. When we collect every pair, a match that moves neither pointer finds the same pair forever.
- Sorting when the indexes matter. Sorting moves the values. If the problem wants the original indexes, keep each value with its index before sorting, or use a hash map.
- Overflow with four values. Four values of 10⁹ add up to 4 × 10⁹, more than a 32-bit integer holds. Add them in a 64-bit type.
The sign for pointers from both ends is a sorted array, or one we may sort, and a question about a pair. The same pointers fit a few other shapes:
- A pair or a triple with a target. Sort if needed, then move the end the total points to.
- The best pair. Move the end that has already found its best, like the shorter wall.
- A string read from both ends, as in a palindrome check. Both pointers move every step, as when the strings lesson reversed a word.
- Rearranging in place, or merging two sorted arrays. These use pointers that move the same way, with one pointer in each array for a merge.
Practice it
- Valid PalindromeEasy
- Two Sum II - Input Array Is SortedMedium
- 3SumMedium
- Container With Most WaterMedium
- 4SumMedium
- Trapping Rain WaterHard
- Squares of a Sorted ArrayEasy
- 3Sum ClosestMedium
- Boats to Save PeopleMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.