M14 · Two Pointers

Two Pointers: Opposite Ends and Read/Write

Two indices that only ever move forward (or toward each other) can replace a nested loop. This lesson shows the two shapes of the pattern on sorted arrays, proves that every pointer move discards only impossible answers, and covers overflow and in-place pitfalls in C#, Python, Java and C++.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M14 Two Pointers · 1 of 1 lessons available

You will be able to

  • Trace the opposite-ends scan for a pair with a target sum and say which pairs each pointer move rules out.
  • Argue why the scan never skips a valid pair, using the sorted order and an invariant.
  • Use a read pointer and a write pointer to compact an array in place in one pass.
  • Explain why both scans are O(n) time and O(1) extra space, and when a hash set is the better tool.
  • Avoid integer overflow in the pair sum in C#, Java and C++.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A nested loop over an array looks at every pair (i, j): about n²/2 of them. The two-pointer technique keeps just two indices and moves one of them at every step, never backwards. If each move can be justified ("no answer uses the position I am leaving"), the whole search takes at most n steps.

The pattern comes in two shapes:

  • Opposite ends. left starts at the first element, right at the last, and they move toward each other until they meet. Typical questions: is there a pair with a given sum, which two walls hold the most water, is a string a palindrome.
  • Same direction. Both start at the front. A fast read pointer looks at every element; a slow write pointer marks where the next kept element goes. Typical questions: remove duplicates, move zeros to the end, merge two sorted arrays.

What makes it work is almost always order: a sorted array, or a rule that tells you which side can be discarded. Without that, two pointers is just a guess.

Opposite ends: a pair with a target sum

Given values sorted in ascending order and a target, return two positions whose values add up to the target, or report that none exist.

left = 0, right = n - 1
while left < right:
    sum = values[left] + values[right]
    if sum == target: return (left, right)
    if sum < target:  left  = left + 1
    else:             right = right - 1
return (-1, -1)

Why moving a pointer is safe

Suppose values[left] + values[right] < target. Every other candidate partner of values[left] that is still in range sits between left and right, so it is at most values[right]. If even the largest partner is not enough, none is. So values[left] cannot be part of any answer inside the range, and dropping it loses nothing. That one move rules out right − left pairs at once: (left, left + 1), …, (left, right).

The mirror argument covers sum > target: values[right] overshoots even with the smallest partner left, values[left], so right moves.

This gives the invariant: if a valid pair exists, one exists with both indices inside [left, right]. It holds at the start (the range is the whole array), each move preserves it, and when left ≥ right no two distinct positions remain, so returning "no pair" is correct. The lab's Pairs ruled out metric adds up right − left per move; on the No pair preset it reaches n(n − 1)/2 = 28, every pair of 8 elements, after only 7 sums.

Watch the Pair found preset: 1 + 11 = 12 is too large, so 11 is dropped; 1 + 8 = 9 is too small, so 1 is dropped; and so on until 4 + 6 = 10.

Duplicates and "the same element twice"

left < right guarantees two different positions. Two equal values at different positions are a valid pair ([1, 2, 5, 5, 11, 12] with target 10 returns the two 5s), while a single element never pairs with itself: [5] with target 10 has no pair. If the question asks for all pairs of distinct values, skip over runs of equal values after a match instead of returning.

Complexity

Time Extra space
Nested loops (every pair) O(n²) O(1)
Sort, then two pointers O(n log n) + O(n) O(1) to O(n), depending on the sort
Already sorted, two pointers O(n): at most n − 1 sums O(1)
Hash set of seen values (unsorted input) O(n) expected O(n)

On unsorted input, sorting first costs O(n log n) and loses the original positions (sort indices instead of values if you need them). A hash set answers the unsorted question in expected O(n) time but needs O(n) memory. The problem bank has both: Two prices that fit the budget exactly (sorted, two pointers) and Two readings that add up to a target (unsorted, hash map).

Same direction: read and write

Remove duplicates from a sorted array in place and return the number of distinct values k; the first k slots must hold them in order.

if n == 0: return 0
write = 1                       # values[0..write) are distinct
for read in 1 .. n-1:
    if values[read] != values[write - 1]:
        values[write] = values[read]
        write = write + 1
return write

Invariant: values[0..write) holds every distinct value of values[0..read), once each, in order. Because the array is sorted, equal values are adjacent, so comparing with the last kept value values[write − 1] is enough to know whether values[read] is new.

Writing never destroys data still needed: write ≤ read at all times, so the slot being overwritten has already been read. When no duplicate has been seen yet, write == read and the copy is a harmless self-assignment (the lab labels it as such).

Each element is read once and written at most once: O(n) time, O(1) extra space. The slots from k on keep leftover values; the caller is expected to ignore them (that is also the contract of C++ std::unique).

Recognising the pattern

Reach for two pointers when:

  • the input is sorted (or sorting it is acceptable), and the question is about pairs, triples or a partition;
  • a comparison tells you which end to discard (sum too small: move left; too big: move right);
  • the task asks to rearrange or filter in place without extra memory (read/write).

Be careful when:

  • the input is unsorted and positions matter: sorting destroys them;
  • the decision is not monotonic. For "maximum water between two walls" the rule is "move the shorter wall", which needs its own proof; see Two walls that hold the most water.

Practice in the problem bank

Opposite ends: Two prices that fit the budget exactly, Two walls that hold the most water, Does the phrase read the same both ways?.

Same direction and partitioning: Keep one copy of each sorted value, Push the empty slots to the end, Merge two sorted lists into the first one, Red, white and blue in one pass (three pointers).

Language notes

Overflow. values[left] + values[right] can exceed the range of a 32-bit int. In C# and Java the sum silently wraps around to a negative number (C# throws only inside a checked block); in C++ signed overflow is undefined behaviour, so the compiler may assume it never happens. The listings widen before adding: (long)values[left] + values[right] in C# and Java, std::int64_t{values[left]} + values[right] in C++, and take the target as a 64-bit value. Python integers have arbitrary precision, so the Python listing needs nothing special. The tests in C#, Java and C++ include pairs near int.MaxValue / INT_MAX.

Indices. The C++ version uses signed std::ptrdiff_t for left and right: with right = size − 1, an empty span needs right = −1, which an unsigned std::size_t would turn into a huge number.

Built-ins for the same-direction case.

Language Remove adjacent duplicates Notes
C# no in-place built-in; values.Distinct() (LINQ) Distinct allocates a new sequence and works on unsorted input too (it hashes)
Python list(dict.fromkeys(values)) new list, keeps first occurrences in order; O(n) expected
Java Arrays.stream(values).distinct().toArray() new array, keeps encounter order
C++ values.erase(std::unique(values.begin(), values.end()), values.end()) in place, exactly this read/write algorithm; only removes adjacent duplicates

The teaching implementation

PairWithSum / pair_with_sum and RemoveDuplicates / remove_duplicates are written the same way in all four languages so the lab can highlight matching lines. Every language reads one shared fixture (empty, one element, two elements, equal values, a value that must not pair with itself, negatives, extremes). Because the scan is deterministic, the fixture pins the exact pair returned, not just "some pair". Each language also compares both functions with a brute-force pair search and its own deduplication on 2,000 random sorted arrays.

Common mistakes

  • Running it on unsorted input. The "too small, move left" argument needs sorted order; on unsorted data the scan silently misses pairs.
  • left <= right. That lets an element pair with itself.
  • Moving both pointers after a miss. Only one side is proven useless; moving both can skip the answer.
  • Comparing with values[read − 1] after overwriting. In the read/write loop, compare with the last kept value values[write − 1], which is never overwritten.
  • Forgetting the empty array in the read/write version (write = 1 would be wrong).

Edge cases

  • Empty array or one element: no pair; the distinct prefix has length 0 or 1.
  • All values equal: a pair exists only if the target is twice that value; deduplication keeps one.
  • Target below the two smallest values or above the two largest: one pointer walks all the way and the search ends with no pair after n − 1 sums.

Worked practice

1. In [2, 3, 5, 8, 13] with target 16, which sums are checked?

Answer

2 + 13 = 15 (too small, left moves), 3 + 13 = 16: found at indices 1 and 4. Two sums.

2. Why can't the opposite-ends scan move right when the sum is too small?

Answer

Moving right left only makes the larger value smaller, so the sum gets even smaller. The useless element is values[left]: even its largest remaining partner was not enough.

3. How would you count pairs with sum ≤ target in a sorted array in O(n)?

Answer

Same pointers. If values[left] + values[right] ≤ target, then values[left] works with every index in (left, right], so add right − left and move left. Otherwise move right.

4. What does RemoveDuplicates return for [1, 1, 1], and what is in the array afterwards?

Answer

It returns 1. The array still holds [1, 1, 1]: slot 0 is the distinct prefix, slots 1 and 2 are leftovers that the caller ignores.

Summary

  • Two pointers replace a nested loop when each move can be proven to discard only impossible answers.
  • Opposite ends on sorted data: too small moves left, too big moves right; invariant "a valid pair, if any, lies in [left, right]".
  • Same direction: read visits everything, write marks the end of the kept prefix; write ≤ read makes in-place writes safe.
  • O(n) time, O(1) extra space; widen sums to 64 bits in C#, Java and C++.

Full implementation

Both scans in four languages, each checked against one shared fixture (empty, one element, duplicates, negatives, a value that must not pair with itself, extremes) and 2,000 random sorted arrays compared with a brute-force pair search and the language's own deduplication; C#, Java and C++ also test sums near the 32-bit limit.

namespace Bekadan.Dsa.Examples.ArrayPatterns;
 
/// <summary>
/// The two-pointer technique on an array sorted in ascending order.
/// Both methods run in O(n) time and O(1) extra space; neither checks that
/// the input is sorted.
/// </summary>
public static class TwoPointers
{
    /// <summary>
    /// Opposite ends: returns indices (i, j), i &lt; j, with
    /// values[i] + values[j] == target, or (-1, -1). The sum is computed in
    /// <see cref="long"/>: two ints near int.MaxValue would overflow an int.
    /// </summary>
    public static (int Left, int Right) PairWithSum(ReadOnlySpan<int> values, long target)
    {
        int left = 0, right = values.Length - 1;
        while (left < right)
        {
            long sum = (long)values[left] + values[right];
            if (sum == target)
                return (left, right);
            if (sum < target)
                left++;   // values[left] is too small even with the largest partner left
            else
                right--;  // values[right] is too large even with the smallest partner left
        }
        return (-1, -1);
    }
 
    /// <summary>
    /// Same direction: removes duplicates in place and returns the new length k.
    /// values[0..k) then holds each distinct value once, in order; the slots
    /// after it keep leftover values.
    /// </summary>
    public static int RemoveDuplicates(Span<int> values)
    {
        if (values.Length == 0) return 0;
        int write = 1;  // values[0..write) are distinct
        for (int read = 1; read < values.Length; read++)
        {
            if (values[read] != values[write - 1])
            {
                values[write] = values[read];
                write++;
            }
        }
        return write;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/ArrayPatterns/TwoPointers.cs

"""The two-pointer technique on a list sorted in ascending order.
 
Both functions run in O(n) time and O(1) extra space. Neither checks that the
input is sorted. Python ints never overflow, so sums need no widening.
"""
 
from collections.abc import MutableSequence, Sequence
 
 
def pair_with_sum(values: Sequence[int], target: int) -> tuple[int, int]:
    """Opposite ends: indices (i, j), i < j, with values[i] + values[j] == target, or (-1, -1)."""
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return left, right
        if total < target:
            left += 1  # values[left] is too small even with the largest partner left
        else:
            right -= 1  # values[right] is too large even with the smallest partner left
    return -1, -1
 
 
def remove_duplicates(values: MutableSequence[int]) -> int:
    """Same direction: remove duplicates in place and return the new length k.
 
    values[:k] then holds each distinct value once, in order; the slots after
    it keep leftover values (the list is not shortened).
    """
    if not values:
        return 0
    write = 1  # values[:write] are distinct
    for read in range(1, len(values)):
        if values[read] != values[write - 1]:
            values[write] = values[read]
            write += 1
    return write

Tested on CPython 3.14.0 · examples/python/dsa_examples/two_pointers.py

package dev.bekadan.dsa.patterns;
 
/**
 * The two-pointer technique on an array sorted in ascending order. Both
 * methods run in O(n) time and O(1) extra space; neither checks that the input
 * is sorted.
 */
public final class TwoPointers {
    private TwoPointers() {
    }
 
    /**
     * Opposite ends: returns {i, j}, i &lt; j, with values[i] + values[j] == target,
     * or {-1, -1}. The sum is computed in {@code long}: two ints near
     * Integer.MAX_VALUE would overflow an int.
     */
    public static int[] pairWithSum(int[] values, long target) {
        int left = 0, right = values.length - 1;
        while (left < right) {
            long sum = (long) values[left] + values[right];
            if (sum == target) {
                return new int[] {left, right};
            }
            if (sum < target) {
                left++; // values[left] is too small even with the largest partner left
            } else {
                right--; // values[right] is too large even with the smallest partner left
            }
        }
        return new int[] {-1, -1};
    }
 
    /**
     * Same direction: removes duplicates in place and returns the new length k.
     * values[0..k) then holds each distinct value once, in order; the slots
     * after it keep leftover values.
     */
    public static int removeDuplicates(int[] values) {
        if (values.length == 0) {
            return 0;
        }
        int write = 1; // values[0..write) are distinct
        for (int read = 1; read < values.length; read++) {
            if (values[read] != values[write - 1]) {
                values[write] = values[read];
                write++;
            }
        }
        return write;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/patterns/TwoPointers.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// The two-pointer technique on a span sorted in ascending order. Both functions
// run in O(n) time and O(1) extra space; neither checks that the input is sorted.
 
// Opposite ends: indices {i, j}, i < j, with values[i] + values[j] == target, or
// {-1, -1}. The sum is computed in std::int64_t: two ints near INT_MAX would
// overflow an int, which is undefined behaviour in C++.
// Signed indices: with right = size - 1, an empty span must give right = -1.
inline std::pair<std::ptrdiff_t, std::ptrdiff_t> pair_with_sum(std::span<const int> values, std::int64_t target) {
    std::ptrdiff_t left = 0, right = std::ssize(values) - 1;
    while (left < right) {
        const std::int64_t sum = std::int64_t{values[left]} + values[right];
        if (sum == target) {
            return {left, right};
        }
        if (sum < target) {
            ++left;  // values[left] is too small even with the largest partner left
        } else {
            --right;  // values[right] is too large even with the smallest partner left
        }
    }
    return {-1, -1};
}
 
// Same direction: removes duplicates in place and returns the new length k.
// values[0, k) then holds each distinct value once, in order (what std::unique
// does); the slots after it keep leftover values.
inline std::size_t remove_duplicates(std::span<int> values) {
    if (values.empty()) return 0;
    std::size_t write = 1;  // values[0, write) are distinct
    for (std::size_t read = 1; read < values.size(); ++read) {
        if (values[read] != values[write - 1]) {
            values[write] = values[read];
            ++write;
        }
    }
    return write;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/two_pointers.hpp

References