Paths Subjects Questions Quizzes Pricing Search

Two Pointers

Solve array and string problems in linear time by walking two indices instead of one

Two Pointers

The two-pointer technique replaces a single index with two (or occasionally more) indices that move through a data structure — usually an array or string — according to some rule, so that the total work stays linear instead of quadratic. Instead of comparing every element to every other element with nested loops, you let two positions walk toward each other, away from each other, or side by side at a fixed distance, and you use what you learn at each step to decide how to move them next. The technique doesn't require extra data structures, which is why it's prized in interviews: it turns an O(n^2) brute force into an O(n) pass with O(1) extra space.

There are a few common shapes the pattern takes. Converging pointers start at opposite ends of a sorted array and move toward the middle — this is the shape behind pair-sum and container-area problems, where comparing the values at the two ends tells you which side to move inward. Same-direction pointers (often called slow/fast or read/write pointers) start together and one races ahead of the other, which is the shape behind in-place array rewrites like moving zeros to the end or removing duplicates. Fixed-gap pointers keep a constant distance apart as they slide together, useful for sliding-window-adjacent problems. Palindrome checks are a special case of the converging pattern applied to strings, scanning inward from both ends and bailing out as soon as a mismatch appears.

Reach for two pointers when the data is sorted (or can cheaply be sorted) and you're looking for pairs, triplets, or a running comparison between "small" and "large" elements; when you need to check symmetry, like a palindrome; or when you need to rewrite an array in place without allocating a second array. It is not the right tool when the input is unsorted and order matters for the answer (in that case a hash map is usually faster, since sorting would cost O(n log n) and possibly change relative ordering you needed to preserve) — though hybrid approaches often sort once and then use two pointers to search the sorted result.

A generic template for the converging variant looks like this:

left, right = 0, len(arr) - 1
while left < right:
    if condition_met(arr[left], arr[right]):
        # record answer, then move one or both pointers
        left += 1
        right -= 1
    elif need_bigger_value:
        left += 1
    else:
        right -= 1

The same-direction, in-place variant looks like:

write = 0
for read in range(len(arr)):
    if should_keep(arr[read]):
        arr[write], arr[read] = arr[read], arr[write]
        write += 1

Because each pointer only ever moves forward (or the two only ever move toward each other), the total number of pointer moves is bounded by the size of the input, giving O(n) time. No auxiliary array is needed, so space is O(1) beyond the input itself — a meaningful advantage over hash-map-based alternatives when memory is constrained.

Common pitfalls: off-by-one errors when deciding whether the loop condition should be left < right or left <= right; forgetting to skip over duplicate values when generating triplets or pairs, which silently produces duplicate answers; forgetting to sort the array first when the problem doesn't guarantee sorted input (the pattern typically depends on it); and mutating the array while reading from it in a way that skips or reprocesses an element.

This subject walks through six problems that showcase these variants: finding a pair that sums to a target in a sorted array, finding all triplets that sum to zero, validating a string as a palindrome in place, maximizing the area between two lines (container with most water), shifting zeros to the end of an array while preserving order, and computing the next lexicographical permutation of an array in place.

Ready to test your knowledge?

Practice questions

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.