Two Pointers

Learn the two pointers technique with interactive palindrome, 3Sum and trapping rain water examples. Follow pointer decisions and compare with brute force.

The pattern

Two Pointers: two indices that close in on the answer

Instead of trying every pair (O(n²)), keep two indices and move them based on what you see. The trick is always the same argument: one of the two values can't be part of any better answer, so it's safe to step past it for good. That turns n² pairs into n steps.

134571011LRwalk towards each other

1Start at both ends

One pointer at the smallest value, one at the largest. Each step moves one of them inwards, so the whole thing takes at most n steps.

134571011LR1 + 11 = 12 > 9sum too big → R moves leftsum too small → L moves right

2Every move rules one out

Target 9: 1 + 11 = 12 is too big. 11 is too big even with the smallest number, so it can't be in any answer: cross it out and move R.

level = shorter wallmove the shorter wall

3Move the side that limits you

For walls and water, the shorter wall caps the level. Keeping it while the width shrinks can't help, so the shorter side is the one to move.

How to spot it

  • The input is sorted (or sorting it is allowed) and you need a pair or triplet with some sum.
  • “Palindrome”, “reverse”, “mirror”: compare from both ends.
  • Maximise something that depends on the distance between two positions and the smaller of their values.
  • “In place, O(1) extra memory”: two indices instead of a hash map.

Three shapes of two pointers

  • Opposite ends, moving inwards: every problem on this page.
  • Fast and slow: one moves twice as fast, as in Floyd's cycle detection.
  • Both from the left, as a window: that's the Sliding Window pattern, NeetCode's next category.

NeetCode 150 · Two Pointers

All 5 problems

Pick a problem to see it solved step by step. They're in NeetCode's order, roughly easiest first.

Valid Palindrome

EasyBlind 75

Given a string, return true if it reads the same forwards and backwards once you ignore upper/lower case and remove everything that isn't a letter or digit.

Input

s = "A man, a plan, a canal: Panama"

s

A
L
␣
m
a
n
,
␣
a
␣
p
l
a
n
,
␣
a
␣
c
a
n
a
l
:
␣
P
a
n
a
m
a
R

variables

L
0
R
29

Press Play or Step to watch the solution run.

Step 0 / 21
900 ms

Brute force vs the pattern

On this input:

Pattern: O(n)
19 ops
Brute force
n/a

The obvious way builds a cleaned copy of the string and compares it with its reverse. That's O(n) time too, but it needs O(n) extra memory. Two pointers checks in place with O(1) memory.

“ops” counts basic steps: lookups, inserts, comparisons, array reads. On tiny inputs brute force can even win, because it may stumble on the answer early; as n grows, the gap opens up.

How it works: Valid Palindrome

Step by step

  • L and R
  • Matched pair
  • Mismatch

Press Start or Step: the step the animation is on lights up below.

  1. 1

    Pointers at both ends

    L at index 0, R at the last index.

    l, r = 0, len(s) - 1
  2. 2

    Skip what doesn't count

    Move a pointer past spaces and punctuation.

    if not s[l].isalnum(): l += 1
  3. 3

    Match → move both inwards

    Same character (ignoring case): this pair is fine.

    l += 1; r -= 1
  4. 4

    Mismatch → not a palindrome

    One differing pair is enough to say no.

    return False
  5. 5

    Pointers met → palindrome

    Every pair matched.

    return True

A palindrome's first character matches its last, its second matches its second-to-last, and so on. So put one pointer at each end and walk them towards each other, comparing as you go.

Characters that don't count (spaces, punctuation) are simply skipped by whichever pointer is on them. Nothing is copied, so memory stays O(1).

Spot it in an interview

  • “Reads the same both ways”, “mirror”, “reverse in place”: pointers at both ends moving inwards.
  • Whenever you'd compare position i with position n − 1 − i.
time O(n)space O(1)

Each step moves at least one pointer inwards, so there are at most n steps, and nothing is copied.

Credits

Learn more from NeetCode

The problem list and order come from the NeetCode 150 by NeetCode (neetcode.io). The solutions here follow the approaches NeetCode teaches in the linked videos; the animations, explanations and code were written for CodeQuest. If these help, NeetCode's videos and site are well worth your time.

Problem statements are summarised in our own words; the full versions are on LeetCode.