Arrays and strings · Beginner

Two pointers

Walk two indices through a sequence, from both ends or at two speeds, so every step rules out candidates and one pass replaces a nested loop.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

A nested loop looks at every pair of positions. Two pointers look at one pair at a time and use what they learn to discard a whole row or column of pairs at once. That only works when the data has an order the comparison can exploit: a sorted array, a palindrome read from both ends, or a "read" index that is always ahead of a "write" index.

There are two shapes. Opposite ends: left starts at 0, right at n − 1, and one of them moves inward on every step. Same direction: a fast read pointer scans every element while a slow write pointer marks where the next kept element goes.

How to recognise it

  • The input is sorted (or sorting it first is acceptable) and you look for a pair or a triple with a target property.
  • The task asks to rearrange, compact or partition an array in place with O(1) extra space.
  • You compare an element with its mirror: palindromes, reversals, symmetric checks.
  • A brute-force solution checks all pairs, and moving one side can be shown to never skip the answer.

When not to use it

  • The input is unsorted and order matters for the answer (indices must be reported): sorting loses the original positions, so a hash map is usually the better tool.
  • You need every pair, not one pair: the output itself is quadratic and no pointer trick avoids that.
  • The decision about which pointer to move does not follow from the comparison; if you cannot argue why a discarded pair is useless, the pattern does not apply.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

# Opposite ends (sorted input, pair with a target sum)
left, right = 0, len(a) - 1
while left < right:
    s = a[left] + a[right]
    if s == target: return (left, right)
    if s < target: left += 1     # a[left] is too small even for the largest remaining partner
    else:          right -= 1    # a[right] is too big for every remaining left
return none

# Same direction (keep elements that satisfy keep(x), in place)
write = 0
for read in range(len(a)):
    if keep(a[read]):
        a[write] = a[read]
        write += 1
return write                     # a[0:write] holds the kept elements in order
  • Each iteration moves at least one pointer, and neither pointer moves backwards, so the loop runs at most n times.
  • For the opposite-ends shape, write down the invariant: "no pair outside [left, right] is a solution". Each move must preserve it.

Complexity

Time O(n), extra space O(1). Linear because the pointers together travel at most n positions. If you sort first, the sort dominates at O(n log n).

Worked examples

Pair sum on [1, 3, 4, 6, 9], target 10

left = 1, right = 9: sum 10, done. With target 7: 1 + 9 = 10 is too big, so 9 can never be used (every other partner is ≥ 1); right moves to 6. 1 + 6 = 7, found. Three comparisons instead of ten pairs.

Compacting [0, 5, 0, 2, 7] by dropping zeros

read visits every index; write starts at 0. 5 is kept and copied to index 0, 2 to index 1, 7 to index 2. write ends at 3, so the first three slots are [5, 2, 7]; the tail can then be filled with zeros if the task asks for it.

Pitfalls

  • Using `left <= right` when a pair needs two distinct elements: the loop then pairs an element with itself.
  • Moving both pointers after a match when duplicates matter (counting all pairs needs care with runs of equal values).
  • Forgetting that sorting changes indices; return values instead, or sort index-value pairs.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.two-pointers · version 1