Pointer Technique

Two Pointers

Place one pointer at each end of a sorted array and move them inward based on the current sum. Converts O(n²) brute-force pair-search into O(n) — one of the most used interview patterns.

What is the two pointers technique?

The two pointers technique uses two indices that move through an array, often from both ends towards the middle, to solve a problem in one O(n) pass instead of nested O(n²) loops. It works best on sorted arrays (pair sums, removing duplicates) and on symmetric problems like palindromes and reversing in place.

function pairWithSum(sorted, target) {     // O(n) on a sorted array
  let l = 0, r = sorted.length - 1;
  while (l < r) {
    const sum = sorted[l] + sorted[r];
    if (sum === target) return [l, r];
    sum < target ? l++ : r--;               // move the pointer that helps
  }
  return null;
}
pairWithSum([1, 3, 4, 6, 9], 10);   // [0, 4]  → 1 + 9

Two Sum — animated trace

twoSum([1,3,6,8,11], target=9)step 1/2

// Array state

1
L
3
[1]
6
[2]
8
[3]
11
R
→ nums=[1,3,6,8,11], target=9. left=0(1), right=4(11). sum=12>9, right--

// Pseudocode

1// Two Sum on sorted array — O(n) time, O(1) space
2function twoSum(nums, target):
3 left = 0
4 right = len(nums) - 1
5 while left < right:
6 sum = nums[left] + nums[right]
7 if sum == target:
8 return [left, right]
9 else if sum < target:
10 left++ // need larger value
11 else:
12 right-- // need smaller value
13 return [] // not found

Container with most water — trace it

container-water.pseudo
1
2
3
4
5
6
7
8
9
10
11
12
13

// Trace output

Click ▶ Run to trace execution

Palindrome check

palindrome.pseudo
1// Palindrome check — O(n) time, O(1) space
2function isPalindrome(s):
3 left = 0
4 right = len(s) - 1
5 while left < right:
6 if s[left] != s[right]: return false
7 left++
8 right--
9 return true

Complexity

Two sum (sorted array)O(n)

Linear time

Palindrome checkO(n)

Linear time

Container with most waterO(n)

Linear time

3Sum — fix one, two-pointer for remainingO(n²)

Quadratic time

Space — only pointer variablesO(1)

Constant time

💡Prerequisites
Two pointers on a pair-sum problem requires a sorted array. The sorted invariant lets you reason: if the current sum is too small, move left pointer right (increases sum); if too large, move right pointer left (decreases sum). Without sorting, this logic breaks.

🎯 Quick Check

You run two-pointer two-sum on an unsorted array. Is this correct?

Two Pointers Technique: summary

Key points

  • Opposite-ends pointers suit sorted data and palindromes; same-direction pointers suit in-place filtering.
  • Sorting first (O(n log n)) often unlocks a two-pointer solution.
  • Fast and slow pointers are a variant used on linked lists.

Frequently asked questions

›When should I use two pointers?

When the data is sorted or symmetric and you're looking for pairs, removing items in place, or comparing from both ends.