The two-pointer technique walks two indices through a sequence in a coordinated way, so that every step rules out candidates that provably cannot be the answer. It turns many O(n²) "check every pair" searches into a single O(n) pass with O(1) extra memory. It comes in three flavors: pointers converging from opposite ends, pointers moving in the same direction (a reader and a writer), and one pointer per input when merging two sorted sequences.
Think of it like
Pairing dancers in a height-sorted line
Dancers stand in a line sorted by height, and you need a pair whose combined height is exactly 340 cm. Start with the shortest and the tallest. If together they are too short, the shortest dancer is hopeless: even the tallest partner was not enough, so send them away. If they are too tall, the tallest dancer is hopeless for the mirror reason. Every comparison sends one person home, so you finish after at most n comparisons instead of trying every pair.
How to recognize it
Brute force examines all n(n-1)/2 pairs. Two pointers works whenever the input has enough structure (usually sortedness or a monotone quantity) that one comparison tells you which pointer can safely move. Look for these signals:
| If the problem says... | Think... | Flavor |
|---|---|---|
| Sorted array, find a pair or triple with a target sum | Start at both ends, move the side that is too small or too large | Opposite ends |
| Palindrome, reverse in place, symmetric comparison | Compare s[lo] and s[hi], move both inward | Opposite ends |
| Maximize area or width between two boundaries | Start wide, discard the limiting boundary | Opposite ends |
| Remove, deduplicate or compact elements in place with O(1) space | A fast reader and a slow writer | Same direction |
| Partition by a predicate (zeros to the end, evens first, three colors) | Writer marks the boundary of the kept region | Same direction |
| Two sorted arrays or lists: merge, intersect, compare | One pointer per input, advance the smaller | Two inputs |
| Linked list cycle or middle | Pointers at different speeds, see Fast & Slow Pointers | Same direction |
Opposite ends
lo = 0,hi = n - 1, loop whilelo < hi- Each step moves one pointer inward
- Needs a monotone rule: moving
loincreases, movinghidecreases - Pair sum, 3Sum, container with most water, palindromes
Same direction
readvisits every element,writetrails behinda[0..write)always holds the answer built so far- Works in place with O(1) extra space
- Remove duplicates, move zeroes, partitioning
Two inputs
iwalks array A,jwalks array B- Advance whichever points at the smaller value
- O(n + m) total work
- Merge step of merge sort, intersections, diffing
Opposite-direction pointers
Place lo at the start and hi at the end. Look at the pair, decide which pointer is useless, move it, repeat. The loop runs at most n - 1 times because the gap hi - lo shrinks by at least one each step.
def converge(a, target):
lo, hi = 0, len(a) - 1
while lo < hi:
current = evaluate(a[lo], a[hi])
if current == target:
return lo, hi # or record it and keep going
if current < target:
lo += 1 # a[lo] cannot be part of any remaining answer
else:
hi -= 1 # a[hi] cannot be part of any remaining answer
return NonePair sum in a sorted array
Find two values in [1, 3, 4, 6, 8, 11] that add up to 10. The visualization above runs exactly this kind of search: watch how each comparison discards one end.
| Step | lo (value) | hi (value) | Sum | Decision |
|---|---|---|---|---|
| 1 | 0 (1) | 5 (11) | 12 | Too big: 11 is too large even for the smallest partner, so hi-- |
| 2 | 0 (1) | 4 (8) | 9 | Too small: 1 is too small even for the largest partner, so lo++ |
| 3 | 1 (3) | 4 (8) | 11 | Too big, hi-- |
| 4 | 1 (3) | 3 (6) | 9 | Too small, lo++ |
| 5 | 2 (4) | 3 (6) | 10 | Found: indices 2 and 3 |
Why it never misses a valid pair
Picture every pair (i, j) with i < j as a cell in the upper triangle of an n × n grid. Brute force visits every cell. Two pointers starts at the top-right corner (0, n-1) and each move deletes an entire row or column of the grid without looking at it. The only question is whether those deletions are safe.
Symmetrically, if the sum is too large then a[i] + a[hi] ≥ a[lo] + a[hi] > target for every i ≥ lo, so column hi can be discarded. Neither move can skip a solution.
Container with most water
Given wall heights, pick two walls that hold the most water: area = min(h[lo], h[hi]) × (hi - lo). Start with the widest container. Then always move the shorter wall inward.
Why is that safe? Suppose h[lo] ≤ h[hi]. Every other container that uses wall lo is narrower than the current one, and its height is still capped by h[lo]. So none of them can beat the area we just measured, and wall lo can be discarded. Moving the taller wall instead could never help: the width shrinks while the height stays capped by the same short wall.
Valid palindrome
Compare s[lo] with s[hi] and move both inward. For LeetCode's version, skip characters that are not letters or digits and compare case-insensitively. The variant "valid palindrome after deleting at most one character" tries both s[lo+1..hi] and s[lo..hi-1] at the first mismatch, still O(n).
3Sum: fix one, two-pointer the rest
- 1
Sort
Sorting costs O(n log n) and unlocks the two-pointer rule. It also groups duplicates together.
- 2
Fix an anchor
For each index
i, look for pairs innums[i+1..]that sum to-nums[i]. - 3
Skip duplicate anchors
If
nums[i] == nums[i-1], every triple it would find was already found. Skip it. - 4
Converge
Run the pair-sum scan on the suffix. On a match, record it, move both pointers, then skip repeated values of
nums[lo]. - 5
Stop early
If
nums[i] > 0, every remaining value is positive and no triple can sum to zero.
Total time is O(n²): n anchors, each with an O(n) scan. The same idea generalizes to kSum in O(n^(k-1)) by fixing k - 2 values with nested loops or recursion.
Same-direction pointers
Here both pointers move left to right. read visits every element; write marks where the next kept element goes. The invariant is that a[0..write) is exactly the output for the elements read so far, which is why the technique works in place.
def compact(a):
write = 0
for read in range(len(a)):
if keep(a, read, write): # problem-specific predicate
a[write] = a[read]
write += 1
return write # new logical length| read | a[read] | Kept? | Array prefix a[0..write) |
|---|---|---|---|
| 0 | 1 | Yes (first element) | [1] |
| 1 | 1 | No, equals a[write-1] | [1] |
| 2 | 2 | Yes | [1, 2] |
| 3 | 3 | Yes | [1, 2, 3] |
| 4 | 3 | No | [1, 2, 3] |
[1, 1, 2, 3, 3]: the answer is length 3. Elements beyond write are leftover junk the caller ignores.Move zeroes and partitioning
To move zeroes to the end while preserving the order of the non-zero values, swap each non-zero a[read] into a[write]. Swapping (instead of copying) leaves the zeros behind automatically. The Lomuto partition step of Quick Sort is the same pattern with the predicate a[read] < pivot.
def sort_colors(a: list[int]) -> None:
low, mid, high = 0, 0, len(a) - 1
# a[0..low) = 0s, a[low..mid) = 1s, a[mid..high] = unknown, a(high..] = 2s
while mid <= high:
if a[mid] == 0:
a[low], a[mid] = a[mid], a[low]
low += 1
mid += 1
elif a[mid] == 1:
mid += 1
else:
a[mid], a[high] = a[high], a[mid]
high -= 1 # do not advance mid: the swapped-in value is unexaminedMerging two sorted arrays
With one pointer per input, compare A[i] and B[j], emit the smaller and advance that pointer. Each step consumes one element, so merging costs O(n + m). This is the combine step of Merge Sort, and small changes give intersection (advance both on equality), union, and "is B a subsequence of A".
Complexity
Each iteration moves at least one pointer, and pointers only move in one direction, so the total number of iterations is bounded by the total distance the pointers can travel: O(n) for one array, O(n + m) for two. If the input must be sorted first, the O(n log n) sort dominates.
Two pointers or a hash map?
Two pointers
- Needs sorted input (or a monotone property)
- O(1) extra space
- Naturally enumerates all pairs and handles duplicates
- Sorting loses original indices unless you sort
(value, index)pairs
Hash map
- Works on unsorted input in one O(n) pass
- O(n) extra space
- Returns original indices directly
- Clumsy for "closest to target" or range conditions
Edge cases
- Empty array or a single element: the
while lo < hiloop never runs, so return the "not found" value. - Use
lo < hi, notlo <= hi, when an element may not pair with itself. - Integer overflow when adding two large values in Java or C++: compare
a[lo] > target - a[hi]or use 64-bit sums. - All elements equal (for example
[0, 0, 0, 0]in 3Sum): the answer is one triple, not four. - Unsorted input passed to a sorted-only algorithm silently gives wrong answers. Sort or switch to hashing.
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Pair sum (sorted) | O(n) | O(1) | At most n - 1 pointer moves |
| 3Sum | O(n²) | O(1) | Plus O(n log n) to sort; output not counted |
| Container with most water | O(n) | O(1) | Always move the shorter wall |
| Remove duplicates / move zeroes | O(n) | O(1) | Reader and writer, in place |
| Merge two sorted arrays | O(n + m) | O(n + m) | O(1) extra when merging from the back in place |
If the input is not already sorted, add O(n log n) for sorting.
Implementation
The pair-sum scan, then 3Sum built on top of it with duplicate skipping.
def two_sum_sorted(a: list[int], target: int) -> tuple[int, int]:
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
if s == target:
return lo, hi
if s < target:
lo += 1 # a[lo] is too small for every remaining partner
else:
hi -= 1 # a[hi] is too large for every remaining partner
return -1, -1
def three_sum(nums: list[int]) -> list[list[int]]:
nums.sort()
n = len(nums)
res: list[list[int]] = []
for i in range(n - 2):
if nums[i] > 0:
break # all remaining values are positive
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate anchors
lo, hi = i + 1, n - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
res.append([nums[i], nums[lo], nums[hi]])
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip duplicate second values
return resKey takeaways
- Two pointers replaces an O(n²) pair search with an O(n) scan when each comparison can safely discard one candidate.
- Opposite-end pointers rely on sortedness: the invariant is "if an answer exists, it is inside
[lo, hi]". - Same-direction pointers (reader and writer) compact or partition an array in place with O(1) extra space.
- Merging two sorted sequences uses one pointer per input and costs O(n + m).
- 3Sum is sorting plus one anchor plus a pair-sum scan: O(n²), with careful duplicate skipping.
Common pitfalls
- Applying the converging scan to an unsorted array, where the discard argument no longer holds.
- Moving the taller wall in container with most water, which can skip the optimal container.
- Reporting duplicate triples in 3Sum because equal anchors or equal second values are not skipped.
- Merging in place from the front and overwriting values that have not been read yet.
- Using
lo <= hiand pairing an element with itself.
Interview tips
- When you see "sorted" plus "pair" or "triple", say "two pointers" and state the invariant before coding.
- Explain why a move is safe (which row or column of pairs you are discarding); interviewers love the proof.
- If the input is unsorted and indices matter, compare sorting (O(n log n), O(1) space) against hashing (O(n), O(n) space) out loud.
Real-world applications
- The merge step in merge sort and in external sorting of huge files.
- Diffing and intersecting sorted lists such as posting lists in search engines.
- In-place filtering and compaction in memory-constrained code.
- Partitioning in quick sort and quickselect.
Practice problems
Test yourself
In a sorted array, a[lo] + a[hi] is smaller than the target. Which move is guaranteed not to skip a solution?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.