Skip to the content

Lesson 123 of 296

Two pointers

What you will learn

  • The two pointers pattern and its two forms
  • Valid Palindrome
  • Two Sum on a sorted array
  • 3Sum
  • Container With Most Water
  • Trapping Rain Water
On this page

The idea

Instead of one index, use two, and move them according to a rule. This often replaces a nested loop (O(n²)) with a single pass (O(n)).

Two common forms:

FormHowTypical use
Opposite endsleft starts at 0, right at the end; they move towards each otherSorted arrays, palindromes, pairs
Same directionBoth start at the left; one reads, one writes, or one leadsRemoving items in place (Lesson 118), fast and slow (Lesson 124)

Opposite-ends pointers usually need the data to be sorted or symmetric, so that moving one pointer has a predictable effect.

Valid Palindrome

Problem (LeetCode 125): is the string a palindrome (reads the same both ways), ignoring case and anything that is not a letter or digit?
"A man, a plan, a canal: Panama" → true.

TypeScript
function isAlphaNumeric(ch: string): boolean {
  return /[a-z0-9]/i.test(ch);
}

function isPalindrome(s: string): boolean {
  let left = 0;
  let right = s.length - 1;
  while (left < right) {
    while (left < right && !isAlphaNumeric(s[left]!)) left++;
    while (left < right && !isAlphaNumeric(s[right]!)) right--;
    if (s[left]!.toLowerCase() !== s[right]!.toLowerCase()) return false;
    left++;
    right--;
  }
  return true;
}

O(n) time, O(1) space. (Cleaning the string first and comparing with its reverse also works, but uses O(n) extra space; mention both.)

Two Sum II: sorted input

Problem (LeetCode 167): the array is sorted. Find two numbers that add to target. Return 1-based indexes. Use O(1) extra space.

Idea: start with the smallest and largest.

  • Sum too small? Move left right to get a bigger number.
  • Sum too big? Move right left to get a smaller number.
TypeScript
function twoSumSorted(numbers: number[], target: number): [number, number] | null {
  let left = 0;
  let right = numbers.length - 1;
  while (left < right) {
    const sum = numbers[left]! + numbers[right]!;
    if (sum === target) return [left + 1, right + 1];
    if (sum < target) left++;
    else right--;
  }
  return null;
}

O(n) time, O(1) space. Why it works: if the sum is too small, the current left cannot be part of any answer with any number at or below right, so it is safe to discard it.

3Sum

Problem (LeetCode 15): find all unique triplets that add to 0.
[-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]].

Brute force: three nested loops, O(n³), plus duplicate handling.

Idea: sort. Fix the first number nums[i], then solve Two Sum II on the rest with two pointers, looking for -nums[i]. Skip equal values to avoid duplicate triplets.

TypeScript
function threeSum(nums: number[]): number[][] {
  const sorted = [...nums].sort((a, b) => a - b);
  const result: number[][] = [];

  for (let i = 0; i < sorted.length - 2; i++) {
    const first = sorted[i]!;
    if (first > 0) break;
    if (i > 0 && first === sorted[i - 1]) continue;

    let left = i + 1;
    let right = sorted.length - 1;
    while (left < right) {
      const sum = first + sorted[left]! + sorted[right]!;
      if (sum < 0) {
        left++;
      } else if (sum > 0) {
        right--;
      } else {
        result.push([first, sorted[left]!, sorted[right]!]);
        left++;
        right--;
        while (left < right && sorted[left] === sorted[left - 1]) left++;
        while (left < right && sorted[right] === sorted[right + 1]) right--;
      }
    }
  }
  return result;
}
  • if (first > 0) break: after sorting, if the smallest of the three is positive, no sum can be 0.
  • The two continue/while skips prevent duplicate triplets.

O(n²) time (sorting is O(n log n), smaller than n²). O(1) extra space besides the sorted copy and output.

Container With Most Water

Problem (LeetCode 11): height[i] is a vertical line. Choose two lines that, with the x-axis, hold the most water. Area = min(height[left], height[right]) × (right - left).

Idea: start with the widest container (both ends). The area is limited by the shorter line. Moving the taller line inwards can never help (the width shrinks and the height is still capped by the shorter one). So always move the shorter line.

TypeScript
function maxArea(height: number[]): number {
  let left = 0;
  let right = height.length - 1;
  let best = 0;
  while (left < right) {
    const h = Math.min(height[left]!, height[right]!);
    best = Math.max(best, h * (right - left));
    if (height[left]! < height[right]!) left++;
    else right--;
  }
  return best;
}

O(n) time, O(1) space.

Trapping Rain Water

Problem (LeetCode 42, hard): given bar heights, how much rain water is trapped between them?
[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] → 6.

Key fact: water above position i = min(highest bar on the left, highest bar on the right) - height[i] (if positive).

Simple approach: precompute maxLeft[i] and maxRight[i] arrays: O(n) time, O(n) space.

Two pointers, O(1) space: keep leftMax and rightMax as you move inwards. Always move the side with the smaller max: on that side, the water level is decided by its own max, because the other side is known to have something at least as tall.

TypeScript
function trap(height: number[]): number {
  let left = 0;
  let right = height.length - 1;
  let leftMax = 0;
  let rightMax = 0;
  let water = 0;
  while (left < right) {
    if (height[left]! < height[right]!) {
      leftMax = Math.max(leftMax, height[left]!);
      water += leftMax - height[left]!;
      left++;
    } else {
      rightMax = Math.max(rightMax, height[right]!);
      water += rightMax - height[right]!;
      right--;
    }
  }
  return water;
}

O(n) time, O(1) space. In an interview, explain the prefix/suffix max version first, then improve it.

How to say it in an interview

"Two pointers replace a nested loop when moving one pointer has a predictable effect, usually on sorted or symmetric data. From opposite ends, I move the pointer that cannot be part of a better answer: the smaller side in sorted Two Sum, the shorter line in Container With Most Water. 3Sum sorts, fixes one number and runs two pointers on the rest, skipping duplicates, for O(n squared). Trapping Rain Water uses the rule that water at a position is the smaller of the left and right maximums minus its height, computed with two pointers in O(1) space."

Key words

WordMeaning
Two pointersTwo indexes moving through data by a rule
Opposite endsPointers starting at both ends and moving inwards
TripletA group of three items
Prefix / suffix maximumThe largest value before / after a position

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.