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.
leftstarts at the first element,rightat 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
readpointer looks at every element; a slowwritepointer 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 valuevalues[write − 1], which is never overwritten. - Forgetting the empty array in the read/write version (
write = 1would 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 movesright; invariant "a valid pair, if any, lies in[left, right]". - Same direction:
readvisits everything,writemarks the end of the kept prefix;write ≤ readmakes in-place writes safe. - O(n) time, O(1) extra space; widen sums to 64 bits in C#, Java and C++.