Skip to content

Lesson 6 of 40Core patterns

Two Pointers

Walk two indices through an array, from both ends or at two speeds, to solve pair and in-place problems in O(n).

15 min read0/4 questions

Many array problems look like they need every pair of elements, which is O(n²). Two pointers solves a big family of them in a single pass with O(1) extra memory. It shows up constantly in interviews ("pair in a sorted array", "palindrome", "remove in place", "3Sum") and it is the pattern that makes sorting first worth paying for.

The idea: keep two indices into the array and move them according to a rule, so that each step rules out part of the search for good.

Opposite ends on sorted input

Find two numbers in a sorted array that add up to a target. Start one pointer at each end.

  • If the sum is too big, move the right pointer left (to a smaller number).
  • If the sum is too small, move the left pointer right (to a bigger number).
  • If it matches, you are done.
Pair summing to 10 in a sorted array
1
0
↑L
3
1
4
2
6
3
8
4
11
5
↑R
sum = 12

1 + 11 = 12, too big. Nothing pairs with 11: even the smallest number overshoots. Move R left.

1/5

Why is it safe to throw a number away? When nums[L] + nums[R] is too big, nums[R] plus any number at or right of L is at least as big, because the array is sorted. So nums[R] cannot be in any answer, and you lose nothing by dropping it.

Quick check
The sum nums[L] + nums[R] is smaller than the target. Why move L and not R?
Need a nudge? A hint rules out a wrong answer.
Python
def pair_sum_sorted(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 else: right -= 1 return [] print(pair_sum_sorted([1, 3, 4, 6, 8, 11], 10))print(pair_sum_sorted([1, 2, 3], 100))
Output
Press Run (⌘ Enter) to see what happens.

The same "squeeze from both ends" shape checks palindromes: compare s[left] and s[right], and move both inward while they match.

Predict the outputPython

What does this print?

s = "racecar"
left, right = 0, len(s) - 1
steps = 0
while left < right and s[left] == s[right]:
  left += 1
  right -= 1
  steps += 1
print(steps)
Need a nudge? Hints walk you through it.
ChallengeEasy

Valid Palindrome

A phrase is a palindrome if it reads the same forwards and backwards once you lowercase every letter and throw away everything that is not a letter or digit. Given a string s, return true if it is a palindrome.

"A man, a plan, a canal: Panama"  →  true    ("amanaplanacanalpanama")
"race a car"                      →  false   ("raceacar")
" "                               →  true    (nothing left, which counts)

Try to solve it without building a cleaned-up copy of the string.

Constraints

  • 0 <= s.length <= 2 * 10^5
  • s contains only printable ASCII characters.
  • Use O(1) extra space.
def is_palindrome(s: str) -> bool: # Compare from both ends, skipping anything that is not a letter or digit. pass

Same direction: read and write pointers

The second flavour moves both pointers the same way. A fast read pointer looks at every element; a slow write pointer marks where the next element you want to keep should go. This rearranges an array in place, with O(1) extra space.

Move all zeros to the end, keeping the other numbers in order:

Move zeroes with read and write pointers
0
0
↑w↑r
1
1
0
2
3
3
12
4

r reads a 0. Zeros are not kept, so w stays put.

1/5
Python
def move_zeroes(nums): write = 0 for read in range(len(nums)): if nums[read] != 0: nums[write], nums[read] = nums[read], nums[write] write += 1 nums = [0, 1, 0, 3, 12]move_zeroes(nums)print(nums)
Output
Press Run (⌘ Enter) to see what happens.

The same skeleton removes duplicates from a sorted array, removes all copies of a value, or partitions numbers around a pivot. Change the "is this a keeper?" test and you have a new solution.

Why sorting first can be worth it

Two pointers needs sorted input. Sorting costs O(n log n). That sounds like a loss next to the O(n) hash map approach, so when is it worth it?

  • When you need O(1) extra space and are allowed to modify the input. A hash map costs O(n) memory.
  • When the brute force is O(n²) or worse. For 3Sum (three numbers adding to 0), sorting costs O(n log n) and then fixing one number plus a two-pointer scan costs O(n²) total, down from O(n³).
  • When sorted order makes skipping duplicates easy: equal values sit next to each other, so you can step over them.

What you lose: the original indices. If the question asks for positions in the original array, either use a hash map or sort (value, index) pairs.

Put it in order4 steps

Put the 3Sum approach in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Common mistakes

  • Using left <= right in a pair search, so an element pairs with itself. Use left < right.
  • Forgetting the input must be sorted. On unsorted input the "rule out" argument breaks and you will miss answers.
  • Not skipping duplicates in 3Sum, producing the same triple several times.
  • Moving both pointers when only one should move, skipping valid pairs.
  • Returning sorted indices when the problem wanted original ones.
Quick check
You run the opposite-ends pair search on the unsorted array [8, 1, 6, 3] with target 9. What happens?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

3Sum

Given a list of integers nums, return every unique triplet [a, b, c] of values taken from three different positions where a + b + c == 0. Two triplets with the same values count as the same triplet, so do not repeat them. The order of the triplets, and of the values inside each one, does not matter.

nums = [-1, 0, 1, 2, -1, -4]   →  [[-1, -1, 2], [-1, 0, 1]]
nums = [0, 1, 1]               →  []
nums = [0, 0, 0, 0]            →  [[0, 0, 0]]

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
def three_sum(nums: list[int]) -> list[list[int]]: # Sort first, then fix one number and solve Two Sum on the rest. pass
Key terms
two pointers
Two indices that move through an array by a rule so each step rules out part of the search.
opposite ends
One pointer at each end, squeezing inward. Used for pair sums on sorted input and palindromes.
read/write pointers
A fast pointer reads every element; a slow pointer marks where the next kept element goes. Rearranges in place.
in place
Changing the input array directly using O(1) extra memory instead of building a new one.
3Sum
Find triples summing to zero: sort, fix one number, then two-pointer the rest. O(n²).
Interview pattern: Two Pointers31 problemsSpot it: Sorted input · pairs that sum to a target · palindromes · in-place