Pattern 01 / 10 · Fundamentals
Two Pointers
Walk in from both ends and let the data tell you which side to move.
The idea
Start one pointer at each end. Each step looks at the pair and moves exactly one pointer inward, so every step throws away a candidate that can never be the answer. One pass, no nested loop.
Reach for it when
- The array is sorted, or you can sort it without losing the answer.
- You are looking for a pair (or triple) that meets a condition.
- You need to compare or swap items from the two ends, like palindromes.
Watch it run
167. Two Sum II – Input Array Is Sorted
Given a sorted array, find the two numbers that add up to target and return their 1-based indices.
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2.
Input: numbers = [2, 3, 4], target = 6
Output: [1, 3]
Explanation: The sum of 2 and 4 is 6. Therefore, index1 = 1, index2 = 3.
Input: numbers = [-1, 0], target = -1
Output: [1, 2]
Explanation: The sum of -1 and 0 is -1. Therefore, index1 = 1, index2 = 2.
WALKTHROUGH INPUT · numbers = [1, 3, 4, 6, 8, 11, 14], target = 17
Put left at the start (index 0) and right at the end (index 6).
1function twoSum(numbers: number[], target: number): number[] {2let left = 0, right = numbers.length - 1;3while (left < right) {4const sum = numbers[left] + numbers[right];5if (sum === target) return [left + 1, right + 1];6if (sum < target) left++;7else right--;8}9return [];10}