Algorithm · Array techniques · O(n)
Two pointers
Two indices that move through an array under a rule: pair sums from both ends of a sorted array, or in-place filtering with read and write pointers.
The full derivation, edge cases and exercises are in the lesson Two pointers: opposite ends and read/write. Open it full width in the playground.
On this page
The idea
On a sorted array, a pair sum that is too small can only grow by moving the left pointer right, and one that is too large can only shrink by moving the right pointer left. Each step discards a whole row of candidate pairs, so one pass replaces the O(n²) double loop.
With read and write pointers moving the same way, the write pointer marks the end of the kept prefix: removing duplicates or zeros in place in one pass.
Steps
- Opposite ends: start at 0 and n − 1; compare the sum with the target and move the pointer that can fix it.
- Same direction: read every element; copy it to the write position only if it should be kept.
Invariants
What holds at every step; the correctness argument rests on these.
- Opposite ends: no pair outside [left, right] can be the answer.
- Same direction: a[0 … write) is the filtered prefix of a[0 … read).
Complexity
| Case | Time | Extra space |
|---|---|---|
| Either form | O(n) | O(1) |
When to use it
Use it when
- Sorted input with a pair or triple condition, palindromes, in-place filtering and partitioning.
Avoid it when
- The input is unsorted and sorting would lose information you need (indices): use a hash map.
Step through it
The interactive lab for two pointers: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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 < 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 < 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
Learn more
Lessons
- Two pointers: opposite ends and read/write· M14 Two Pointers
Data structures it uses
Problems, patterns and exercises
- PatternTwo pointers· O(n)
- ProblemTwo prices that fit the budget exactly· beginner · O(n)
- ProblemDoes the phrase read the same both ways?· beginner · O(n)
- ProblemKeep one copy of each sorted value· beginner · O(n)
- Complexity exerciseTwo pointers moving toward each other· Θ(n)