Two Pointers Pattern

Master the two pointers technique for efficient array traversal

beginner

Two Pointers Pattern

The Two Pointers technique uses two pointers to traverse a data structure, often from opposite ends or at different speeds.

When to Use

  • Working with sorted arrays
  • Finding pairs that satisfy a condition
  • In-place array modifications
  • Reducing O(n²) to O(n)

Interactive Visualization

This example finds two numbers that sum to a target value:

Two Sum with Two Pointers

Interactive
110151222283354405
Sorted

Find two numbers that sum to 50 in sorted array

Speed
Step 1 of 8
Implementation
javascript
1function twoSum(arr, target) {
2 // Array must be sorted
3 let left = 0;
4 let right = arr.length - 1;
5
6 while (left < right) {
7 const sum = arr[left] + arr[right];
8
9 if (sum === target) {
10 return [left, right];
11 } else if (sum < target) {
12 left++;
13 } else {
14 right--;
15 }
16 }
17 return null; // No pair found
18}

How It Works

  1. Initialize two pointers (usually start and end)
  2. Calculate current result based on pointer positions
  3. Move pointers based on comparison with target:
    • Too small? Move left pointer right
    • Too big? Move right pointer left
    • Found? Return result

Complexity

MetricComplexity
TimeO(n)
SpaceO(1)

Common Variations

Opposite Ends

Start from both ends, move towards center.

Same Direction

Both pointers start from same end, move at different speeds.

Slow & Fast Pointer

One moves 1 step, other moves 2 steps (cycle detection).

Practice Problems

  1. Container With Most Water
  2. 3Sum
  3. Remove Duplicates from Sorted Array
  4. Valid Palindrome

Common Use Cases

  • Finding pairs that sum to target
  • Removing duplicates
  • Reversing arrays
  • Checking palindromes

Related Topics

arrays two-pointers optimization
Ad