Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Arrays & Two Pointers/Two Pointers

Learn the pattern · ~15 min

Two Pointers

also called opposite-ends pointers, read/write pointers, Dutch national flag

On sorted data, put a pointer at each end; every comparison proves one end can't be in any answer, so drop it and move inward.

Signalsarray is sorted, or sorting does not destroy the answerfind a pair/triplet with a target sum or best valuein-place dedupe/partition with O(1) extra space
Cheat sheet and practice

Reach for it when you read

  • +A sorted array (or one you may sort) and you need a pair or triplet with a given sum or difference.
  • +Compare the two ends and close in: palindromes, reversing, pairing the heaviest with the lightest.
  • +A score over a pair, like width × the shorter height, where the weaker side caps the score.
  • +Rewrite an array in place with O(1) extra space: remove duplicates, move zeroes, split into regions.

Not this one when

  • ×Unsorted, and you need the indices of a pair with a sum: a hash map in one pass. Sorting loses the indices.
  • ×A contiguous stretch whose sum or contents must follow a rule: a sliding window. Both pointers go the same way and what's between them matters.
  • ×The closest value to each element, by value: sort it and binary search.

Learn Two Pointers

First, what is a "pointer" here?

In this pattern a pointer is just an index: an int that remembers a position in the array. l = 0 points at the first element, r = n − 1 at the last. Nothing to do with C++ pointers.

Two pointers means you keep two of these indices and move them through the array together. The most common form starts one at each end and walks them inward.

How do two pointers walk inward?

The smallest example: reverse [1, 3, 4, 6, 8, 11] in place. The rule is one line:

Swap the two ends, then move both pointers one step inward. Stop when they meet.

l r what happens array
0 5 swap 1 and 11, then l++ and r-- 11, 3, 4, 6, 8, 1
1 4 swap 3 and 8, then l++ and r-- 11, 8, 4, 6, 3, 1
2 3 swap 4 and 6, then l++ and r-- 11, 8, 6, 4, 3, 1
3 2 l is past r: stop 11, 8, 6, 4, 3, 1

Three swaps for six elements. Each step finishes the two outer positions for good.

The code for it

C++
int l = 0, r = n - 1;
while (l < r) {
    swap(a[l], a[r]);   // both ends are now final
    l++;
    r--;
}

You don't need to memorise this. It's the table: swap the ends, step inward, stop when they meet.

Why l < r and not l <= r? When l == r both point at the middle element (odd length), and swapping it with itself would do nothing.

Fine, but how does this help us?

Here's the classic problem: Two Sum II. The array is sorted. Find two numbers that add up to the target, and return their positions (1-based).

For [1, 3, 4, 6, 8, 11] and target 10, solve it by hand. Go through the numbers and ask what partner each one needs on its right:

number needs is it on the right?
1 9 no
3 7 no
4 6 yes, at position 4
6 4 no (4 is on the left)
8 2 no
11 −1 no

The answer is 4 + 6 = 10, positions [3, 4].

The brute force

The direct way tries every pair.

C++
vector<int> ans;
for (int i = 0; i < n && ans.empty(); i++)
    for (int j = i + 1; j < n; j++)
        if (a[i] + a[j] == target) { ans = {i + 1, j + 1}; break; }

Six numbers give 15 pairs; n numbers give n(n − 1)/2, O(n²). For n = 10⁵ that's about 5 × 10⁹ additions in the worst case. Time limit exceeded.

And it never uses the fact that the array is sorted. That's a hint.

The one thought that fixes it

Put l on the smallest number and r on the largest. The first sum is 1 + 11 = 12, too big.

Now think about 11. Which partner could ever work with it? Its smallest possible partner is 1, the very smallest number in the array, and even that gives 12. Every other partner is bigger, so every other sum with 11 is bigger than 12. 11 is in no answer. Drop it: r--.

Next, 1 + 8 = 9, too small. Now think about 1. Its biggest possible partner left is 8, and even that's not enough. Every other partner is smaller. 1 is in no answer. Drop it: l++.

That's the whole idea:

  • Sum too big? The right number has already met its smallest partner: r--.
  • Sum too small? The left number has already met its biggest partner: l++.
  • Equal? Found it.

Each comparison throws away one number for good: the same inward walk as the reversal. It needs the array sorted; otherwise the smallest partner isn't at l.

C++
int l = 0, r = n - 1;
vector<int> ans;
while (l < r) {
    int sum = a[l] + a[r];
    if (sum == target) { ans = {l + 1, r + 1}; break; }
    if (sum < target) l++;      // a[l] is too small even with the biggest partner
    else r--;                   // a[r] is too big even with the smallest partner
}

Dry run

Same array, [1, 3, 4, 6, 8, 11], target 10.

l r a[l] + a[r] what happens
0 5 1 + 11 = 12 too big: 11 is useless, r--
0 4 1 + 8 = 9 too small: 1 is useless, l++
1 4 3 + 8 = 11 too big: 8 is useless, r--
1 3 3 + 6 = 9 too small: 3 is useless, l++
2 3 4 + 6 = 10 found: positions [3, 4]

[3, 4], the same answer as the brute force.

Why it's O(n)

Count what happens to the gap r − l. It starts at n − 1, and every step shrinks it by exactly 1, because one pointer moves one place inward. So there are at most n − 1 steps: O(n) time, and two integers of extra space, O(1).

From O(n²) down to O(n), by using the sorted order to throw away one number per comparison.

No target, a best score? Move the weaker side

Container With Most Water: bars of height h[i] stand at positions i. Pick two; the water between them is width × min(h[i], h[j]). No target now, so what do we throw away?

Start with the widest pair. The water is capped by the shorter bar, and every pair further in is narrower, so the shorter bar can't do better with anyone left: drop it. On [3, 7, 2, 5, 4, 8, 1, 6], bar 0 (height 3) and bar 7 hold 7 × 3 = 21; any other partner for bar 0 is closer and still capped at 3.

C++
best = max(best, (j - i) * min(h[i], h[j]));
if (h[i] <= h[j]) i++;          // the shorter bar can't do better with anyone narrower
else j--;
i, j heights width area best move
0, 7 3, 6 7 21 21 i
1, 7 7, 6 6 36 36 j
1, 6 7, 1 5 5 36 j
1, 5 7, 8 4 28 36 i
2, 5 2, 8 3 6 36 i
3, 5 5, 8 2 10 36 i
4, 5 4, 8 1 4 36 i

The best is 36: bars 1 and 7. With equal heights either side may move, since neither can win with a narrower partner.

Three numbers? Fix one, squeeze the rest

3Sum asks for every triplet that sums to 0, with no repeats. Sort, fix a[i] with an outer loop, and run the squeeze on i + 1 .. n − 1 looking for −a[i].

C++
if (i > 0 && a[i] == a[i - 1]) continue;   // same fixed value: same triplets again

After a hit, skip equal values for l too. On [-1, 0, 1, 2, -1, -4] (sorted: [-4, -1, -1, 0, 1, 2]) the answer is [-1, -1, 2] and [-1, 0, 1]. That's n squeezes of O(n) each: O(n²), down from O(n³).

Both pointers going the same way? Read and write

Not every two-pointer problem squeezes. In Move Zeroes both indices go left to right: r reads every element, w marks where the next kept one goes.

C++
if (a[r] != 0) swap(a[w++], a[r]);
r a[r] what happens array
0 0 a zero, skip 0, 1, 0, 3, 12
1 1 keep: swap into w = 0, w → 1 1, 0, 0, 3, 12
2 0 a zero, skip 1, 0, 0, 3, 12
3 3 keep: swap into w = 1, w → 2 1, 3, 0, 0, 12
4 12 keep: swap into w = 2, w → 3 1, 3, 12, 0, 0

Everything left of w is kept, in its original order.

Remember this

  • A squeeze needs a reason to drop one end every step: sorted values for sums, "the shorter bar caps it" for water. No reason, no squeeze.
  • Loop while l < r. Move exactly one pointer per comparison, unless you just recorded a hit.
  • Unsorted, and you need the original indices? Sorting would lose them: use a hash map in one pass instead.
  • Whenever a problem asks for "a pair (or triplet) in a sorted array", "compare the two ends" or "rewrite in place with O(1) space", think two pointers.

Practise it on Valid Palindrome (both ends of a string), then Two Sum II, Move Zeroes (read and write), 3Sum (fix one, squeeze), Container With Most Water (best score) and Boats to Save People (pair the heaviest with the lightest).

Below, watch Two Sum II run line by line (its own input, 0-based indices).

Watch it work, line by line

Two Sum II (sorted input) ↗, a = [1, 2, 4, 7, 11, 15], target = 9 → [1, 3] (2 + 7). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is the data sorted (or can I sort it without losing what I need), and does one comparison tell me which end can never be part of the answer?

Reach for it when

  • +array is sorted, or sorting does not destroy the answer
  • +find a pair/triplet with a target sum or best value
  • +in-place dedupe/partition with O(1) extra space
  • +palindrome check from both ends
  • +n up to 1e5-1e6 so O(n2) pair scan is too slow
  • +O(1) extra space demanded

It fails when

  • ×Contiguous subarray under a running constraint (sum, count, distinct)use Sliding window
  • ×Unsorted pair-sum, or sorting would lose the original indices you must returnuse Hash map, O(n)
  • ×Sum-window with negative values: moving a pointer doesn't change the sum monotonicallyuse Prefix sum + hash map
  • ×You need every pair/triplet/combination, not a count or the best oneuse Enumeration / backtracking
  • ×Finding one value against a fixed target, not a relation between two elementsuse Binary search

Looks like it, isn't (and the other way round)

  • Reverse Pairs looks like Two Pointers, needs Divide and Conquer (merge-sort counting)

    Pairs i < j with a[i] > 2a[j] are counted across merge-sort halves (or with a BIT).

  • 132 Pattern looks like Two Pointers, needs Monotonic Stack

    Need the best middle candidate for each position; a decreasing stack scanned from the right tracks it.

  • Max Value of Equation looks like Two Pointers, needs Monotonic Deque

    Rewriting gives a window maximum of (y - x).

  • 4Sum II looks like Two Pointers, needs Hash Map / Hash Set Lookup

    Four separate arrays: hash all a+b sums, look up -(c+d) (meet in the middle with a hash map).

  • Two Sum looks like Two Pointers, needs Hash Map / Hash Set Lookup

    Array is unsorted and indices are needed; sorting would lose them, so use complement lookup.

  • Longest Consecutive Sequence looks like Two Pointers, needs Hash Map / Hash Set Lookup

    O(n) required: start runs only at x where x-1 is absent in a hash set.

  • Find Peak Element looks like Two Pointers, needs Binary Search

    No sortedness, but the local slope gives a monotone predicate for binary search.

  • Maximum of Absolute Value Expression looks like Two Pointers, needs Manhattan <-> Chebyshev Rotation

    Expand the absolute values into 4 sign patterns; each needs only a max and min of a linear form.

Why this pattern and not another

The array is sorted (or sorting is acceptable) and the answer is found by converging from both ends or a same-direction write pointer — each move provably discards a candidate in O(1) space.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1What makes it safe to throw one end away?Reveal

    The order. If the sum is too big with the smallest partner left, the big end is too big with everyone, so it's in no answer.

  • 2Why while (l < r) and not l <= r for pair sums?Reveal

    When l == r there's only one element, and it can't pair with itself.

  • 3Container With Most Water: which pointer moves, and why?Reveal

    The shorter one. The area is capped by the shorter line and the width only shrinks, so keeping it can never give a bigger area.

Practice ladder

every problem →
  1. 1Valid Palindromeboth ends of a stringEasy
  2. 2Two Sum II - Input Array Is Sortedthe hookMedium
  3. 3Move Zeroesread and writeEasy
  4. 43Sumfix one, squeezeMedium
  5. 5Container With Most Waterbest scoreMedium
  6. 6Sort Colorsthree regionsMedium
  7. 7Boats to Save Peoplegreedy pairingMedium
  8. 8Sum of Three Valuesfix one, squeezeMedium
  9. 9Trapping Rain Waterrunning maxHard

Finished Two Pointers? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Two Pointers

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial