Skip to content

Two Pointers

Reach for it when the problem says

  • Sorted input
  • pairs that sum to a target
  • palindromes
  • in-place
Solved
0/31Solved
Problems
31Problems
Variants
5Variants

Problems

5 variants

Converging pointers

0 of 5 solved

Same-direction pointers

0 of 9 solved

Pair sums on sorted input

0 of 8 solved

Two sequences

0 of 4 solved

Reverse and swap

0 of 5 solved

Pattern guide

A nested loop over pairs is O(n²). On 100,000 elements that is ten billion steps, and an interviewer will stop you long before it finishes. Two pointers is the most common way to get that same pair search down to O(n): instead of trying every pair, you keep two indices and use what you just learned to throw away a whole group of pairs with each move.

What it is

A pointer here is just an integer index into a list or string. The pattern keeps two of them and moves them according to a rule, so that every step rules something out for good. Because neither pointer ever moves backward, the total number of moves is at most about 2n.

The classic picture is a sorted list and a target sum. Put left on the smallest value and right on the largest, and let their sum tell you which one to move.

Pair that sums to 13 in a sorted list
1
0
↑L
3
1
4
2
6
3
8
4
11
5
14
6
↑R
sum = 15target = 13

Start at both ends: 1 + 14 = 15, too big. Even the smallest partner is too much for 14, so 14 can never be in the answer.

1/6

The key sentence is "this value can never be in the answer". Every two-pointer solution has a version of it. If you cannot say why a move is safe, you do not have a two-pointer solution yet; you have a guess.

Quick check
In the sorted pair-sum search, the sum nums[L] + nums[R] is too big. Why is it safe to move R left?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"sorted", "non-decreasing"Pointers at both ends, moved by comparing with a target
"pair", "two numbers", "triplet" that sum to a targetSort, fix all but two values, two pointers for the last two
"in place", "O(1) extra space", "do not return anything"A read pointer and a write pointer inside the same list
"palindrome", "reverse", "mirror"One pointer at each end, swapping or comparing inward
"merge", "subsequence", two strings or two listsOne pointer per input, each moving forward
"remove duplicates", "move zeros", "first k elements"Write pointer marks a kept prefix

Constraint clues

ConstraintWhat it tells you
n up to 10^5 or 2 * 10^5O(n²) is out; O(n) or O(n log n)
n up to 3000 with "triplets"O(n²) is expected: sort plus one two-pointer pass per fixed value
n up to 200 with "quadruplets"O(n³) is fine: two fixed loops plus a pointer pass
"Use O(1) extra space"Rules out hash maps and copies; points to pointers on the original data
Values up to 10^9A counting array is out, so sorting plus pointers is often the cleanest

Input and output shape clues

  • One sorted list in, a pair or a count out. Converging pointers or pair sums.
  • One list in, the same list changed, a length out. Read and write pointers moving in the same direction.
  • Two sequences in, one answer out. One pointer per sequence.
  • A string in, a string out with some positions swapped. Reverse and swap from both ends.

Looks like it, but isn't

NeighbourHow to tell them apart
Sliding windowAlso two indices, but the question is about a contiguous range and its contents ("longest substring with…"). Two pointers usually cares about the two endpoints themselves, or about rearranging.
Hash map (Two Sum)If the input is not sorted and you must return original indices, sorting would scramble them. Use a hash map instead.
Binary searchIf you need one value, binary search. If you need a pair and the list is sorted, two pointers beats a binary search per element (O(n) vs O(n log n)).
Fast and slow pointers on a linked listSame idea of two speeds, but on nodes, not indices. Cycle detection lives in the linked list pattern.
Quick check
The list is unsorted and the problem asks for the indices of two values that sum to a target. What is the best tool?
Need a nudge? A hint rules out a wrong answer.

The sub-patterns

Converging pointers

When it applies: the answer depends on comparing or combining something near the front with something near the back. Palindromes, the widest container, squares of a sorted list, trapped water. The pointers start at both ends and move toward each other until they meet.

Valid Palindrome II on abca
a
0
↑L
b
1
c
2
a
3
↑R

a matches a. Matching pairs never need a deletion, so move both inward.

1/3
Python
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True print(is_palindrome("racecar"), is_palindrome("ab"))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Each step moves at least one pointer inward. Best-known problems: Valid Palindrome, Container With Most Water, Trapping Rain Water, Squares of a Sorted Array.

Pair sums on sorted input

When it applies: you need two (or three, or four) values whose sum hits, approaches, or stays under a target, and you are allowed to sort. Fix all but two values with loops, then run converging pointers on the rest. The comparison with the target decides which pointer moves.

3Sum: fix one value, two pointers on the rest
-4
0
-1
1
↑i
-1
2
↑L
0
3
1
4
2
5
↑R
need = 1

Sorted. Fix i at -1, so we need L + R = 1. -1 + 2 = 1: a hit, record [-1, -1, 2].

1/3
Python
def pair_count(nums: list[int], target: int) -> int: nums = sorted(nums) left, right = 0, len(nums) - 1 count = 0 while left < right: total = nums[left] + nums[right] if total == target: count += 1 left += 1 right -= 1 elif total < target: left += 1 else: right -= 1 return count print(pair_count([3, 1, 3, 4, 3], 6))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n log n) for the sort plus O(n) per pass, so O(n) for pairs, O(n²) for triplets, O(n³) for quadruplets. Best-known problems: Two Sum II, 3Sum, 3Sum Closest, Boats to Save People, Number of Subsequences That Satisfy the Given Sum Condition (where a fitting pair contributes 2^(right - left) subsequences at once).

In JavaScript, always pass a comparator to sort: [10, 9, 1].sort() sorts as strings and gives [1, 10, 9].

Predict the outputPython

What does this print?

nums = sorted([1, 5, 2, 4, 3])
left, right = 0, len(nums) - 1
moves = 0
while left < right:
  if nums[left] + nums[right] == 6:
      break
  moves += 1
  left += 1
print(nums[left], nums[right], moves)
Need a nudge? Hints walk you through it.

Same-direction pointers

When it applies: you must change one list in place (remove values, compact it, partition it) or scan it in segments. A read pointer visits every element; a write pointer trails behind and marks the end of the part you have finished. Because write never passes read, you never overwrite a value before you have looked at it.

Move Zeroes with read and write
0
0
↑W↑R
1
1
0
2
3
3
12
4

R sees a zero. Zeros are not kept, so only R moves.

1/4
Python
def compact(nums: list[int], drop: int) -> int: write = 0 for read in range(len(nums)): if nums[read] != drop: nums[write] = nums[read] write += 1 return write data = [3, 2, 2, 3, 4]k = compact(data, 3)print(k, data[:k])
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Best-known problems: Move Zeroes, Remove Duplicates from Sorted Array, String Compression, Longest Mountain in Array.

The keep rule is the only part that changes between problems. "Keep if not zero", "keep if different from nums[write - 1]", "keep if different from nums[write - 2]" (at most two copies). Compare with the kept prefix, not the raw input, because the input has already been overwritten.

Two sequences

When it applies: there are two inputs (two strings, two sorted lists) and you walk both in order. Each input gets its own pointer, and each pointer only moves forward (or only backward). Merging sorted lists, checking a subsequence, and comparing strings after backspaces all fit.

Is abc a subsequence of ahbgdc?
a
0
↑t
h
1
b
2
g
3
d
4
c
5
s = abci = 1

t[0] is a, which matches s[0]. Advance i to look for b next.

1/3
Python
def merge_sorted(a: list[int], b: list[int]) -> list[int]: i = j = 0 out: list[int] = [] while i < len(a) and j < len(b): if a[i] <= b[j]: out.append(a[i]) i += 1 else: out.append(b[j]) j += 1 out.extend(a[i:]) out.extend(b[j:]) return out print(merge_sorted([1, 4, 7], [2, 3, 9, 10]))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n + m) time, where n and m are the two lengths. Space is O(1) beyond any output. Best-known problems: Merge Sorted Array, Is Subsequence, Backspace String Compare, Merge Strings Alternately.

When the output has to go into one of the inputs (Merge Sorted Array), fill it from the back, where the free space is.

Reverse and swap

When it applies: the output is the input with positions mirrored: a reversed string, reversed vowels, reversed letters only, reversed words, or a reversed suffix. Pointers start at both ends and swap instead of compare. Positions that must not move are skipped by moving only that pointer.

Reverse only letters in ab-cd
a
0
↑L
b
1
-
2
c
3
d
4
↑R

Both pointers sit on letters. Swap a and d.

1/3
Python
def reverse_range(chars: list[str], left: int, right: int) -> None: while left < right: chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 word = list("pointers")reverse_range(word, 0, len(word) - 1)print("".join(word))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time. O(1) extra space on a mutable list; O(n) when you must copy an immutable string into a list first. Best-known problems: Reverse String, Reverse Vowels of a String, Reverse Words in a String, Next Permutation.

Next Permutation shows why reverse_range takes a start and an end: after the swap, only the tail to the right of the pivot gets reversed.

Predict the outputPython

What does this print?

nums = [1, 2, 3, 4, 5]
left, right = 1, 3
while left < right:
  nums[left], nums[right] = nums[right], nums[left]
  left += 1
  right -= 1
print(nums)
Need a nudge? Hints walk you through it.

A decision checklist

Read the prompt, then ask in order: Is the result a change to one list in place? Are there two separate inputs? Is the answer a mirrored rearrangement? Is there a target sum on sortable data? Otherwise, is it a front-and-back comparison?

Match the pairs0/5 matched

Match each problem description to the sub-pattern that fits it best.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of the 3Sum solution in order.

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

Traps

  • < versus <=. Converging loops usually run while left < right, because a single element cannot pair with itself. Boats to Save People is the exception: one leftover person still needs a boat, so it runs while light <= heavy.
  • Forgetting to sort. Pair-sum logic is only correct on sorted data. Unsorted input with this logic gives answers that look plausible and are wrong.
  • Sorting when you must return indices. Sorting scrambles positions. Either carry (value, index) pairs or use a hash map instead.
  • Duplicates. In 3Sum and 4Sum, skip repeated values at every level (each fixed loop and the left pointer after a hit). Skip too early and you lose answers like [-1, -1, 2].
  • Comparing with the input instead of the kept prefix. In read/write problems, earlier slots have been overwritten. Compare with nums[write - 1] or nums[write - 2].
  • Only trying one branch. Valid Palindrome II needs both "skip left" and "skip right" checks. Greedy single-branch versions fail on inputs like cbbcc.
  • Writing from the wrong end. When the free space is at the back (Merge Sorted Array), merging from the front overwrites unread values.
  • Overflow. Four values near 10^9 sum past 32 bits. Python and JavaScript are fine; Java and C++ need 64-bit integers.

Edge cases to always test: an empty list (when allowed), one element, two elements, all values equal, no valid answer, and negatives.

Quick check
In Boats to Save People, why does the loop run while light <= heavy rather than while light < heavy?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Quick check
What is the time complexity of 4Sum with sorting, two fixed loops, and a two-pointer pass?
Need a nudge? A hint rules out a wrong answer.
Key terms
Converging pointers
Two indices that start at opposite ends and move toward each other, each step ruling out one element.
Read and write pointers
Two indices moving the same direction in one list: read scans everything, write marks the end of the finished prefix.
Pair-sum template
Sort, fix all but two values, then move two pointers inward based on whether the total is below or above the target.
Elimination argument
The reason a pointer move is safe: the skipped element cannot be part of any better answer.
Stable compaction
Removing elements in place while keeping the survivors in their original order.
Mirror swap
Swapping index i with index n - 1 - i, the core of every in-place reversal.