Skip to content

Two Pointers: Skip Safely with an Invariant in O(1) Memory

Learn the two-pointer technique, why each pointer move never skips an answer, and how to handle crossing pointers, empty input and single items.

11 min readTime: O(n)Memory: O(1)AlgorithmsTwo pointers

Two pointers means walking the same data with two indices at once. Either they start at opposite ends and close in on each other, or they move in the same direction at different speeds. Either way, each step discards part of the search space permanently. That is how you replace an O(n²) scan of every pair, or an O(n) copy of the input, with one O(n) pass and O(1) extra memory. Interviewers rarely care that you know the pattern's name. They want you to say out loud why moving a pointer is safe: what you just threw away could not have held a better answer. This guide builds that argument on a problem that is not one of the linked practice problems, so you can carry the reasoning over to them yourself.

The intuition

The picture to keep in your head.

Picture Pondside, a garden-planning app. A user lines up retaining boards of different heights, one per slot, and wants to pick two of them as the walls of a trough. The trough holds water up to the shorter wall, and its width is the distance between the two slots. Which pair holds the most?

The brute force checks all n(n-1)/2 pairs. Two pointers starts with the widest trough: the first board and the last board. Then it asks which wall is the bottleneck. The shorter one limits the water level. Pair that shorter board with any partner closer in and the width drops, while the level can never rise above the shorter board's height. So every remaining trough that uses the shorter board is no better than the one you just measured. You can drop that board for good and step its pointer inward.

That is the invariant: the best pair you have not yet measured always lies inside the window [left, right]. Each step shrinks the window by one, and the invariant still holds afterwards. When the pointers meet, the window holds no pairs, so the best value you recorded along the way is the answer.

Every two-pointer problem follows the same shape. In a sorted pair-sum, a sum that is too small means the left element cannot reach the target with any partner, so it goes. In a palindrome check, a matched outer pair has nothing more to tell you. In a subsequence check, a matched character can be consumed greedily without losing any possible match. If you cannot state the 'this element is finished' argument, the pattern probably does not apply.

Step by step

Small, safe steps, with the tests passing after each.

  1. Step 1: Place the pointers

    For opposite-end problems, set left = 0 and right = n - 1. For same-direction problems, both usually start at 0, or each pointer starts at the head of its own sequence. Decide now what the window between them means. Here it is: every pair not yet ruled out uses two boards inside [left, right].

  2. Step 2: Pick the loop condition

    Use left < right when the two pointers must refer to two different elements, as in pairs or troughs. Use left <= right only when one element on its own is a meaningful case. An empty or one-item input makes left < right false straight away, so the edge cases need no special code.

  3. Step 3: Evaluate the current pair

    Do the constant-time work for this pair. Compute width times the shorter height and update best. In other problems you would compare two characters, check a sum against the target, or test a match.

  4. Step 4: Move the pointer whose element is finished

    Move the pointer whose element cannot appear in any better answer. Here that is the shorter board. On a tie, move either one: the shorter-or-equal board cannot beat the current trough with a closer partner. Moving the taller board instead could discard the optimum.

  5. Step 5: Stop when the pointers meet or cross

    Once left >= right the window holds no pairs. By the invariant nothing unexamined is left, so return what you recorded. Same-direction variants stop when either pointer runs off the end of its sequence.

What it costs

Time and memory, and why.

Time
O(n)
Memory
O(1)

Each iteration moves exactly one pointer one step inward, so the gap right - left drops by one each time. It starts at n - 1, so there are at most n - 1 iterations of constant work. The only extra state is two indices and a running best, so memory is O(1) no matter how big the input is. Compare this with the brute force, which takes O(n²) time, and with approaches that build a cleaned or reversed copy, which take O(n) extra space.

A traced example

A small input, followed step by step.

Pondside board heights (cm, in slot order): [3, 1, 4, 2, 5, 2]. Find the largest trough area, where area = (right - left) * min(heights[left], heights[right]).

  1. 1left=0 (3), right=5 (2): width 5, level 2, area 10, best=10Start with the widest trough. The right board (2) is shorter, so no closer partner can help it. Move right to 4.
  2. 2left=0 (3), right=4 (5): width 4, level 3, area 12, best=12New best. Now the left board (3) is the bottleneck, so drop it. Move left to 1.
  3. 3left=1 (1), right=4 (5): width 3, level 1, area 3, best=12A board of height 1 caps the water at 1 cm. Drop it. Move left to 2.
  4. 4left=2 (4), right=4 (5): width 2, level 4, area 8, best=12Taller wall, but narrower trough, so not enough. The left board is still shorter. Move left to 3.
  5. 5left=3 (2), right=4 (5): width 1, level 2, area 2, best=12The left board is shorter again. Move left to 4.
  6. 6left=4, right=4: loop endsThe pointers have met, so no pairs are left. The window is empty, and by the invariant every possible better pair was ruled out along the way.

Result: 12: the boards in slots 0 and 4 (heights 3 and 5, distance 4). This took 5 evaluations instead of the 15 pairs a brute force checks.

The code

The same solution in TypeScript, Python and PHP.

// Largest trough formed by two retaining boards.
function maxTrough(heights: number[]): number {
  let left = 0;
  let right = heights.length - 1;
  let best = 0;
  // Invariant: any pair not yet ruled out lies inside [left, right].
  while (left < right) {
    const width = right - left;
    const level = Math.min(heights[left], heights[right]);
    best = Math.max(best, width * level);
    // The shorter board cannot do better with a closer partner, so drop it.
    if (heights[left] <= heights[right]) {
      left++;
    } else {
      right--;
    }
  }
  return best;
}

console.log(maxTrough([3, 1, 4, 2, 5, 2])); // 12
console.log(maxTrough([])); // 0
console.log(maxTrough([7])); // 0

Variants

Shapes the same idea takes.

  • Opposite ends on sorted data

    When: You need a pair, or a triple after fixing one element, that hits a target sum or difference, and the array is sorted or you are allowed to sort it.

    If the sum is too small, the left value cannot reach the target with any partner, so move left. If it is too big, move right. For triples, loop over the first element and run the pair search on the rest. That gives O(n²) instead of O(n³). Skip equal neighbours if the problem asks for unique results.

  • Reader and writer in one array

    When: You must filter or deduplicate an array in place, for example removing duplicates from a sorted list or dropping zeros, using O(1) extra memory.

    The fast pointer reads every element. The slow pointer marks where the next kept element goes. Everything before the slow pointer is already the finished output, and that is the invariant. One pass, no copy.

  • One pointer per sequence

    When: You have two sorted or ordered sequences to merge, intersect, or match against each other, as in checking whether one string is a subsequence of another.

    Advance the pointer whose current item is now finished: the smaller value when merging, or the matched character when checking a subsequence. Matching greedily is safe because using an earlier match never leaves fewer options for the rest.

  • Fast and slow on a linked structure

    When: You need cycle detection, the middle node, or the k-th node from the end of a linked list, without extra memory.

    Move one pointer two steps and the other one step. In a cycle they must meet, because the gap between them shrinks by one each step. When the fast pointer reaches the end, the slow one is at the middle. For k-th from the end, start the fast pointer k nodes ahead instead.

  • Three-way partition

    When: You need to sort values from a tiny set, such as 0, 1 and 2, or split an array around a pivot, in one pass.

    Keep low, mid and high pointers. The region before low is finished on the left, the region after high is finished on the right, and mid scans the unknown middle. Do not advance mid after swapping with high, because the value you just swapped in has not been examined yet.

Common mistakes

What usually goes wrong and how to avoid it.

  • Avoid

    Moving the taller wall, or the larger value, out of habit.

    Better

    Before you code the move, name the element that is finished and say why. Only the bottleneck element can be discarded safely. Moving the other one can skip the optimum.

  • Avoid

    Writing while (left <= right) for pair problems.

    Better

    With <=, an element can pair with itself, for example 4 + 4 = 8 counted from a single 4. Use left < right whenever the answer needs two distinct positions.

  • Avoid

    Using the opposite-ends pair search on unsorted input.

    Better

    The 'too small, so move left' argument relies on sorted order. Sort first, which costs O(n log n), or use a hash set when you have to return original indices.

  • Avoid

    Inner skip loops that run past the other pointer, as in a palindrome check that skips punctuation.

    Better

    Every inner loop needs the guard too: while (left < right && !isAlnum(s[left])) left++. Otherwise a string with no letters at all reads out of bounds.

  • Avoid

    Building a cleaned or reversed copy and calling it two pointers.

    Better

    Compare characters in place, normalizing on the fly, for example by lowercasing each one as you read it. The selling point is O(1) memory, so keep it.

How to recognise it

Clues in a problem statement that call for it.

  • The input is sorted, or sorting it does not break what the question asks.
  • You are asked for a pair or triple that meets a condition, and checking all pairs would be O(n²).
  • The answer depends on the two ends of a range, such as width times the smaller height.
  • You must compare a sequence with its mirror image: symmetry, palindromes, reversal checks.
  • You must modify an array in place with O(1) extra memory: remove, deduplicate, partition.
  • You walk two sequences together and want to know whether one fits inside the other or how they merge.
  • A linked list question asks about cycles, the middle node, or a position counted from the end.

Common questions

Short answers to the usual doubts.

How do I prove moving a pointer is safe during the interview?

State an exchange argument in one sentence. 'Every pair that still uses the shorter board has a smaller width and a level no higher than this board, so none of them can beat the area I just recorded.' Then say the invariant: the best pair not yet examined lies inside [left, right]. That is usually all the interviewer is looking for.

What happens with an empty array or a single element?

With left = 0 and right = n - 1, an empty array gives right = -1 and a single element gives right = 0. In both cases left < right is false, the loop never runs, and you return the initial value. Say this out loud instead of adding special-case branches.

How is two pointers different from a sliding window?

A sliding window is the same-direction form where the range between the pointers is the object you care about, like a substring or subarray, and you maintain an aggregate over it. Opposite-end two pointers usually care only about the two elements at the ends. The safety argument is the same in both: whatever you drop past a pointer is finished.

When should I use a hash set instead?

Use a hash set when the input is unsorted and you need the original indices, or when sorting is not allowed. It gives O(n) time but O(n) memory. If the data is already sorted, or memory is constrained, two pointers wins on memory.

What about ties, when both ends are equal?

Work out whether either move is safe. In the trough problem it is, because the shorter-or-equal board cannot do better with a closer partner, so moving either one keeps the invariant. In pair-sum problems that count all pairs, equal runs need extra care: count the duplicates in a block instead of stepping one element at a time.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide2 of 2 · Pointer traversalsSliding window: contiguous runs in a single passRead the next one