Skip to content

Two pointers: walking an array from both ends

Working knowledgeConcept

Finding two values that add up to a target looks like a job for every pair, and n values have about n²/2 of them. In a sorted array, two indexes, one at each end, rule out a whole row of pairs with every move.

01 Every pair, or something better

The question: in [1, 2, 4, 5, 6, 8, 10, 15], which two values add up to 13? The plain answer tries every pair: 1 with each value after it, then 2 with each value after it, and so on.

Python
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return i, j

Eight values make 8 × 7 / 2 = 28 pairs. A thousand values make about 500,000. The loop works on any array, sorted or not, and that is exactly its weakness: it ignores the one fact that could save it work.

02 Two indexes, one at each end

Put L on the smallest value and R on the largest. Add them. If the sum is too big, move R left to a smaller value. If it is too small, move L right to a bigger one. Stop when the sum hits the target or the two meet.

The table below the array holds all 28 sums. Watch how much of it each move crosses out.

Find two values that add up to 13
Step 1 of 7
Pairs still possible 28
8 sorted values
L10
21
42
53
64
85
106
R157
Sum of every pair (row + column)
245681015
1356791116
2678101217
4910121419
511131520
6141621
81823
1025
  • between L and R
  • the pair to sum next
  • ruled out
  • the answer

Eight sorted values make 28 pairs, and any of them could add up to 13. L starts at the smallest value and R at the largest.

13 target

03 Why one sum rules out a whole row

Look at the first move. 1 + 15 = 16 is too big. Every other value 15 could pair with sits between L and R, and in a sorted array they are all at least 1. So every pair with 15 is at least 16. You never need to try them: one sum told you about seven pairs.

The other direction is the mirror image. When 1 + 10 = 11 is too small, 10 is the biggest partner 1 has left, so every pair with 1 is at most 11. 1 can go.

Each move throws away one value for good, and the pairs it took with it are pairs that could not work. With n values, L and R meet after at most n − 1 moves.

Every pairn(n−1)/2 sums28 sums for 8 values, about 500,000 for 1,000. Works on any order.
Two pointersat most n − 1 sums7 sums at most for 8 values, 999 for 1,000. Needs sorted order.

The whole argument rests on one fact: everything between L and R is at least nums[L] and at most nums[R]. Take away sorted order and a too-big sum tells you nothing about the other pairs.

04 The loop in code

The code is shorter than the argument. Each comment says which value just ran out of useful partners.

pair_with_sum.py
def pair_with_sum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return left, right
if total < target:
left += 1 # nums[left] is too small for every partner left
else:
right -= 1 # nums[right] is too big for every partner left
return None
nums = [1, 2, 4, 5, 6, 8, 10, 15]
print(pair_with_sum(nums, 13))
print(pair_with_sum(nums, 100))
Text
$ python3 pair_with_sum.py
(3, 5)
None

while left < right, not <=: when the two meet there is one value left, and a value cannot pair with itself. The loop runs at most n − 1 times and uses no extra memory, so it is O(n) time and O(1) space.

05 The same move in other problems

The pattern is always the same: a comparison tells you that one of the two values can never be part of a better answer, so you drop it. What changes is the comparison.

Where two pointers turn up
ProblemWhere the pointers startWhich one moves, and why
Pair with a given sumBoth endsToo big: `R` moves, its column is too big. Too small: `L` moves.
Container with most waterBoth endsThe shorter wall. It caps the water level, and every narrower container with that wall holds no more.
Is it a palindrome?Both endsBoth, every step, while the two characters match.
3SumFix one value, then both ends of the restAs for a pair, once per fixed value: `O(n²)` instead of `O(n³)`.
Remove duplicates in placeBoth at the start`fast` reads every value; `slow` moves only when it writes a new one.

The last row is the other family: both pointers start on the left and move at different speeds. It skips no pairs; it lets you read and write the same array in one pass.

06 When it breaks

nums = [8, 1, 15, 4]The input is not sortedA too-big sum then says nothing about the other pairs. Sorting first costs O(n log n) and loses the original indexes; if the problem wants those, as unsorted Two Sum does, a hash map is the better tool.
while left <= right:A value paired with itselfWhen left == right, the sum is one value doubled. For target 10 and a lone 5, the loop reports a pair that does not exist.
if height[l] > height[r]: l += 1Moving the wrong pointerIn Container With Most Water, moving the taller wall never helps: the width shrinks and the shorter wall still caps the level. The proof only holds for the move it was made for.
[-1, -1, 0, 1, 2]Duplicates in 3SumFixing the first -1 and then the second finds [-1, 0, 1] twice. Skip a value equal to the one you just used, for the fixed value and for L and R after a hit.

07 Check yourself

Question

In [1, 3, 6, 9, 12] with target 15, L is on 1 and R on 12. The sum is 13. What does that rule out?

Question

With n sorted values and no pair that works, how many sums does the two-pointer loop compute?

Question

In Container With Most Water the outer walls are 3 and 8. Which do you move inward?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?