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 + 9Two Sum — animated trace
// Array state
// Pseudocode
Container with most water — trace it
// Trace output
Click ▶ Run to trace execution
Palindrome check
1// Palindrome check — O(n) time, O(1) space2function isPalindrome(s):3 left = 04 right = len(s) - 15 while left < right:6 if s[left] != s[right]: return false7 left++8 right--9 return true
Complexity
Linear time
Linear time
Linear time
Quadratic time
Constant time
🎯 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.